-1

I need help to parse this JSON, i have some problems.

  1. The object name is "random"
  2. I need to create Java object with list of generic objects and parse Json
  3. How i can parse every object with random object name.

The Json to Parse example 1 :

{
   "object_name_1":{
      "id":0,
      "value_1":"hello",
      "value_2":"test",

   },
   "object_name_2":{
      "id":1,
      "value_1":"hello",
      "value_2":"test",

   },"object_name_3":{
      "id":2,
      "value_1":"hello",
      "value_2":"test",

   }
} 

The Json to Parse example 2 :

{
   "test_object":{
      "id":0,
      "value_1":"hello",
      "value_2":"test",

   },
   "object_name_2":{
      "id":1,
      "value_1":"hello",
      "value_2":"test",

   },
"new_object":{
      "id":2,
      "value_1":"hello",
      "value_2":"test",

   }
}
  • NB: This is a JSON Object not Json Array and i have output from API so i can't change Json Output

Thank you.

  • answer as always is: iterate the keys (asked so many times that you would find similar question) – Selvin Oct 17 '17 at 10:49
  • Check this [link](https://stackoverflow.com/questions/6455303/dealing-with-randomly-generated-and-inconsistent-json-field-key-names-using-gson), he has same issue like you, this will help – Satender Kumar Oct 17 '17 at 10:51
  • You can use [GSON](http://www.javacreed.com/simple-gson-example/) - here is a small example – Daniel Stiefel Oct 17 '17 at 11:24

1 Answers1

1

This format of json is not Appropriate.you can change format and use array for sequential keys. but you can use below approach:

JSONObject object = new JSONObject(message);
Iterator<String> keyList = object.keys();

while (keyList.hasNext()){
     String key = keyList.next();
     object.get(key);
     //parse value and use it

}
mohamad jalali
  • 372
  • 3
  • 10