Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert javax.json.JsonObject to com.fasterxml.jackson.databind.JsonNode

Tags:

json

jackson

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?

like image 671
Maik Avatar asked Apr 08 '16 07:04

Maik


People also ask

Can we convert JSON to map in Java?

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.

What is Jackson JsonNode?

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.


2 Answers

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.

like image 76
linehrr Avatar answered Oct 13 '22 09:10

linehrr


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;
}
like image 23
cassiomolin Avatar answered Oct 13 '22 10:10

cassiomolin