How to deserialize nested json array using Gson only?
Json input:
{
"players":
[
[
[
"192.168.1.0",
"8888"
],
"id_1"
],
[
[
"192.168.1.1",
"9999"
],
"id_2"
]
],
"result":"ok"
}
I received this message from the server. The server tells me the list of results and players. Each player has a unique identifier and several contact addresses, possibly more than one (ip + port). The hard part for me is the element in the array only matters. It doesn't look like string: value.
Can anyone tell me how to deserialize it using gson?
Thanks in advance.
source to share
What do you players
have Map
, represented as JSON arrays.
It's an ugly card, but still Map
. Key List<String>
(IP and port) with value equal to String
("id")
It's almost like whoever wrote the server made a mistake and did it back, especially given your description of what it should be. It should look like this:
["id_1", [["192.168.1.0", "8888"], [another ip / port], ...]
for each entry. This makes sense since key ( String
) is a key and List<List<String>>
as a value.
This is still ugly as they really have to use an object to represent the IP / Port. Ideally you would like:
["id_1", [{"ip": "192.168.1.1", "port": "8888"}, {"ip": "192.168.1.2", "port": "8889"}]]
The following is how it is 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
8888ID_2
192.168.1.1
9999
You can get some ads and make the map key a little more usable:
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;
in
public Map<IpAndPort, String> players;
in MyClass
source to share