jsonjsonb-api

Extract specific element from JSON using JSON-B


With Jackson we can extract specific element from JSON string and map it to relevant class, like below:

ObjectMapper mapper = new ObjectMapper();
JsonNode root = mapper.readTree(someJson);
JsonNode responseNode = root.get("response");
MyResponse myResponse = mapper.treeToValue(responseNode, MyResponse.class);

How can I achieve the same with JSON-B?


Solution

  • After further reading, it seems like I should not try to do it with JSON-B.
    JSON-B is used for mapping JSON <-> Object, where JSON-P is used for parsing JSON.

    So we can use JSON-P + JSON-B together to accomplish what Jackson can do:

    JsonReader jsonReader = Json.createReader(new StringReader(someJson));
    JsonObject root = jsonReader.readObject();
    JsonObject responseJsonObj = root.getJsonObject("response");
                                
    Jsonb jsonb = JsonbBuilder.create();
    MyResponse myResponse = jsonb.fromJson(responseJsonObj.toString(), MyResponse.class);
                                
    jsonReader.close();