javajsonjacksongson

How to convert list of JsonObject from google json to JsonNode object of Jackson


I have a list of JsonObject which is from google JSON library and then I need to call a third party library which accepts a JsonNode object from the Jackson library.

I don't have much experience with JSON and have been reading about these and from this link knows that JsonNode is a abstract class, hence can't create it and looks like I have to use ObjectNode for storing/converting the JsonObject but looks like it would require some parsing to do that.

How can I convert the JsonObject to ObjectNode?


Solution

  • It could be achieved with the following code:

    private JsonNode toJsonNode(JsonObject jsonObject) throws IOException {
        return mapper.readTree(jsonObject.toString());
    }
    

    To convert back, you may use:

    private JsonObject toJsonObject(JsonNode jsonNode) throws IOException {
        String jsonString = mapper.writeValueAsString(jsonNode);
        JsonParser jsonParser = new JsonParser();
        return jsonParser.parse(jsonString).getAsJsonObject();
    }
    

    Depending on your needs, for a more generic solution, you may consider using JsonElement rather than JsonObject. The code is very similar to the code shown above:

    private JsonNode toJsonNode(JsonElement jsonElement) throws IOException {
        return mapper.readTree(jsonElement.toString());
    }
    
    private JsonElement toJsonElement(JsonNode jsonNode) throws IOException {
        String jsonString = mapper.writeValueAsString(jsonNode);
        JsonParser jsonParser = new JsonParser();
        return jsonParser.parse(jsonString);
    }