8

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?

cassiomolin
  • 124,154
  • 35
  • 280
  • 359
Maik
  • 331
  • 2
  • 4
  • 12

2 Answers2

15
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.

linehrr
  • 1,668
  • 19
  • 24
8

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;
}
cassiomolin
  • 124,154
  • 35
  • 280
  • 359
  • 1
    This it is! Thank you very much :) – Maik Apr 08 '16 at 09:04
  • @frogeyedpeas Is the lack of the import details the reason for the downvote? – cassiomolin Jan 08 '17 at 18:18
  • No I didn't downvote, i only stumbled upon this just now and it seems relevant to something I'm working on. – Sidharth Ghoshal Jan 08 '17 at 18:20
  • @frogeyedpeas I'll consider updating the answer with the import details very soon. For now, the qualified class names on the top of the answer give you a hint. – cassiomolin Jan 08 '17 at 18:24
  • the "Json.create..." line throws me off, this might be an error specific to my environment, but i cant find an import for that – Sidharth Ghoshal Jan 08 '17 at 18:26
  • 1
    @frogeyedpeas Please refer to [`javax.json.Json`](https://docs.oracle.com/javaee/7/api/javax/json/Json.html). It's part of the Java EE 7 and was introduced in the JSR 353, the Java API for JSON Processing. – cassiomolin Jan 08 '17 at 18:31
  • objectMapper.readTree is the buggiest method ever if you have multiple elements with the same name they will be skipped. My advice is do not use readTree (you should actually not use Jackson as well if possible since such thing exists) – jNayden Apr 08 '19 at 13:31