How to deserilize nested array json with only value using Gson? How to deserilize nested array json with only value using Gson? json json

How to deserilize nested array json with only value using Gson?


What you have in players is a Map represented as JSON arrays.

It's an ugly map, but it's still a Map. The key is List<String> (IP and Port) with the value being a String (the "id")

It's almost like whomever wrote the server made a mistake and did it backwards especially given your description of what this is supposed to be. It really should look like:

["id_1",[["192.168.1.0","8888"], [another ip/port], ... ]

for each entry. That would make more sense, with the (String) "id" being the key and List<List<String>> as the value.

That's still ugly as they really should be using object to represent IP/Port. Ideally you would want:

["id_1",[{"ip":"192.168.1.1", "port":"8888"},{ "ip":"192.168.1.2","port":"8889"}]]

Below demonstrates how it's currently written:

public static void main( String[] args ){    String json = "{\"players\":[[[\"192.168.1.0\",\"8888\"],\"id_1\"],[[\"192.168.1.1\",\"9999\"],\"id_2\"]],\"result\":\"ok\"}";    Gson gson = new GsonBuilder().create();    MyClass c = gson.fromJson(json, MyClass.class);    c.listPlayers();}class MyClass {    public String result;    public Map<List<String>, String> players;    public void listPlayers()    {        for (Map.Entry<List<String>, String> e : players.entrySet())        {            System.out.println(e.getValue());            for (String s : e.getKey())            {                System.out.println(s);            }        }    }}

Output:

id_1
192.168.1.0
8888

id_2
192.168.1.1
9999

You can get a bit creative and make the key to the map a little more usable with:

class IpAndPort extends ArrayList<String> {    public String getIp() {        return this.get(0);    }    public String getPort() {        return this.get(1);    }}

then change:

public Map<List<String>, String> players;

to:

public Map<IpAndPort, String> players;

in MyClass