I have a javax.json.JsonObject
and want to validate it against a JSON schema. So I've found the com.github.fge.json-schema-validator
. But it works only with com.fasterxml.jackson.databind.JsonNode
.
Is there a way to convert my JsonObject
into a JsonNode
?
We can easily convert JSON data into a map because the JSON format is essentially a key-value pair grouping and the map also stores data in key-value pairs. Let's understand how we can use both JACKSON and Gson libraries to convert JSON data into a Map.
JsonNode is Jackson's tree model (object graph model) for JSON. Jackson can read JSON into a JsonNode instance, and write a JsonNode out to JSON. This Jackson JsonNode tutorial will explain how to deserialize JSON into a JsonNode and serialize a JsonNode to JSON.
public JsonNode toJsonNode(JsonObject jsonObj) {
ObjectMapper objectMapper = new ObjectMapper();
return objectMapper.readTree(jsonObj.toString());
}
this will just to it. JsonObject.toString() will convert to json String, you don't need to use anything else.
The following solution parses a javax.json.JsonObject
into a JSON string and then parses the JSON string into a com.fasterxml.jackson.databind.JsonNode
using Jackson's ObjectMapper
:
public JsonNode toJsonNode(JsonObject jsonObject) {
// Parse a JsonObject into a JSON string
StringWriter stringWriter = new StringWriter();
try (JsonWriter jsonWriter = Json.createWriter(stringWriter)) {
jsonWriter.writeObject(jsonObject);
}
String json = stringWriter.toString();
// Parse a JSON string into a JsonNode
ObjectMapper objectMapper = new ObjectMapper();
JsonNode jsonNode = objectMapper.readTree(json);
return jsonNode;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With