-3

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.

avy
  • 417
  • 1
  • 9
  • 21
  • post code which you have tried. – user3145373 ツ Sep 02 '16 at 08:46
  • There is an error in your json. It is not valid json – Daniel Sep 02 '16 at 08:47
  • 1
    response Json is invalid. ']' is missing – Abhijeet Sep 02 '16 at 08:48
  • 1
    by ByteString what do you mean?? a string of bytes or google protobuf's ByteString?? – Abhishek Sep 02 '16 at 08:53
  • {"id":81236,"root":0,"child":3,"branch":0,"results":[{"message":"valid"},{"message":"valid"}]} ... here is valid json now – avy Sep 02 '16 at 09:04
  • JSONObject json = new JSONObject("{\"id\":81236,\"root\":0,\"child\":3,\"branch\":0,\"results\":[{\"message\":\"valid\"},{\"message\":\"valid\"}]} ")......................................................but it requires map – avy Sep 02 '16 at 09:05
  • If you're talking about `javax.json.JsonObject`, then what does that have to do with POJO? – Andreas Sep 02 '16 at 09:06
  • @avy Your comment is using `JSONObject`, question is using `JsonObject`. – Andreas Sep 02 '16 at 09:06
  • My json format is not fixed ...it could have any no. of attributes in it...... i need solution for how to convert this plain test into json – avy Sep 02 '16 at 09:07
  • I was trying different possiblities to convert it into Json. – avy Sep 02 '16 at 09:09
  • Are you using `javax.json.JsonObject`, `com.google.gson.JsonObject`, `net.sf.json.JSONObject`, `org.json.JSONObject`, or something else? – Andreas Sep 02 '16 at 09:11

1 Answers1

0

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.
Abhishek
  • 2,485
  • 2
  • 18
  • 25