0

I have a JSONObject response like

{
    "0:"{
        "name": "name1",
        "surname": "surname1",
        "id": "22",
        "motivations": []
    },
    "1:"{
        "name": "name2",
        "surname": "surname2",
        "id": "23",
        "motivations": []
    },
    "2:"{
        "name": "name3",
        "surname": "surname3",
        "id": "24",
        "motivations": []
    },
    "sign": "9e46b7d6b140b",
    "last_call": 1446
}

I want to map it to the List<Person> , but I cant do it before I erased "0:","1:","2:" ,"sign":"9e46b7d6b140b","last_call":1446.

Any idea how to map that in the model?

Rohit5k2
  • 17,948
  • 8
  • 45
  • 57
Expiredmind
  • 788
  • 1
  • 8
  • 29

1 Answers1

1

Create Person class

class Person{
        String name;
        String surname;
        String id;
        String[] motivations;
         //Create getter setter for it
    }

Create HashMap<String,Object> map = new HashMap<>();

map = new Gson().fromJson(responseData, HashMap.class);

And last Iterate over map

Iterator entries = map .entrySet().iterator();

while (entries.hasNext()) {
   String value = (String )entries.next().getValue();
 Object p;
 try{ 
    p = new Gson().fromJson(value , Person .class);
    \\person class
  }
  catch(Exception e)
  {
    // catch exception
    p =null;
  }
  if(p!= null && p instanceOf Person)
  {
     \\create list and add it to the separate list 
    \\ entries.next().getKey()
    \\ entries.next().getValue()
  }
}
Mayur Raval
  • 3,250
  • 6
  • 34
  • 57
  • I cannot implement entries.next().getValue(); (cannot resolve) HashMap map = new Gson().fromJson(response.body(), HashMap.class); Iterator entries = map .entrySet().iterator(); while (entries.hasNext()) { String value = (String )entries.next().getValue(); Log.i(TAG,"cos ma "+value); entries.next(); } – Expiredmind Dec 23 '16 at 12:09
  • 1
    @Expiredmind,Check with http://stackoverflow.com/questions/1066589/iterate-through-a-hashmap I think that will help you – Mayur Raval Dec 23 '16 at 12:29