avy avy - 3 months ago 16
JSON Question

convert ByteString to Json using java

I am getting response from Rest as :

{"id":81236,"root":0,"child":3,"branch":0,"results":[{"message":"valid"},{"message":"valid"}}


I want to convert it into JsonObject using java 8.

I am trying JsonObject but i stucked with the POJO , because Json response may have some additional field sometimes.

So i want to be generic so that any valid json in form of ByteString can be easily converted to JSonObject.

Answer

Assuming you are using org.json.JSONObject, the below works fine...

public static void main(String[] args) {
        String test = "{\"id\":81236,\"root\":0,\"child\":3,\"branch\":0,\"results\":[{\"message\":\"valid\"},{\"message\":\"valid\"}]}";
        JSONObject objJsonObject = new JSONObject(test);
        System.out.println(objJsonObject);
}
  • As pointed out by @Andreas it is not possible for designing a POJO class for a dynamic json object.