あなたが持っているplayers
のはMap
JSON配列として表されています。
それは醜い地図ですが、それでもMap
です。キーはList<String>
(IPとポート)で、値はString
( "id")です。
これは、サーバーを作成した人が間違いを犯し、特にこれがどうあるべきかについての説明を考えると、逆方向に行ったようなものです。実際には次のようになります。
["id_1"、[["192.168.1.0"、 "8888"]、[別のIP /ポート]、...]
エントリごとに。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
8888
id_2
192.168.1.1
9999
次の方法で、少しクリエイティブになり、マップのキーをもう少し使いやすくすることができます。
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