输入的json是:
{
"players":
[
[
[
"192.168.1.0",
"8888"
],
"id_1"
],
[
[
"192.168.1.1",
"9999"
],
"id_2"
]
],
"result":"ok"
}
我从服务器收到此消息。服务器告诉我结果和玩家列表。每个玩家都有一个唯一的ID,以及多个联系地址,可能不止一个(ip+端口)。对我来说困难的部分是数组中的项目只有值(value)。它不像 string:value。
谁能告诉我如何用 gson 反序列化它?
提前致谢。
最佳答案
players
中有什么是 Map
表示为 JSON 数组。
这是一张丑陋 map ,但它仍然是一张Map
。关键是List<String>
(IP 和端口),值为 String
(“id”)
这几乎就像编写服务器的人犯了一个错误并且向后做了,特别是考虑到您对这应该是什么的描述。它确实应该看起来像:
["id_1",[["192.168.1.0","8888"], [another ip/port], ... ]
对于每个条目。这会更有意义,(String
)“id”是关键,List<List<String>>
作为值。
这仍然很丑陋,因为他们确实应该使用对象来表示 IP/端口。理想情况下你会想要:
["id_1",[{"ip":"192.168.1.1", "port":"8888"},{ "ip":"192.168.1.2","port":"8889"}]]
下面演示了它目前的编写方式:
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);
}
}
}
}
输出:
id_1
192.168.1.0
8888id_2
192.168.1.1
9999
您可以发挥一点创意,使 map 的按键更有用:
class IpAndPort extends ArrayList<String> {
public String getIp() {
return this.get(0);
}
public String getPort() {
return this.get(1);
}
}
然后更改:
public Map<List<String>, String> players;
至:
public Map<IpAndPort, String> players;
在 MyClass
关于arrays - 如何使用 Gson 反序列化仅包含值的嵌套数组 json?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14689225/