Reputation: 341
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
?
Upvotes: 8
Views: 23845
Reputation: 1748
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.
Upvotes: 15
Reputation: 130837
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;
}
Upvotes: 8