如何在Java中将带有数字的json对象转换为字段键?

我正在使用的服务器返回一个json对象,其中包含一个对象列表,而不仅仅是一个。

{ "1":{"id":"1","value":"something"}, "2":{"id":"2","value":"some other thing"} } 

我想将此json对象转换为对象数组。

我知道我可以使用Gson,并创建一个这样的类:

 public class Data { int id; String value; } 

然后使用

 Data data = new Gson().fromJson(response, Data.class); 

但它仅适用于json对象内的对象。 我不知道如何将带有数字的json对象转换为键。

或者我需要改变服务器以响应这样的事情?:

 {["id":"1","value":"something"],["id":"2","value":"some other thing"]} 

但我不想更改服务器,因为我必须更改所有客户端代码。

你的JSON看起来很奇怪。 如果您无法更改它,则必须将其反序列化为Map 。 示例源代码可能如下所示:

 import java.lang.reflect.Type; import java.util.HashMap; import java.util.Map; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.reflect.TypeToken; public class GsonProgram { public static void main(String... args) throws Exception { Gson gson = new GsonBuilder().create(); String json = "{\"1\":{\"id\":\"1\",\"value\":\"something\"},\"2\":{\"id\":\"2\",\"value\":\"some other thing\"}}"; Type type = new TypeToken>>() {}.getType(); Map> map = gson.fromJson(json, type); for (Map data : map.values()) { System.out.println(Data.fromMap(data)); } } } class Data { private int id; private String value; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } @Override public String toString() { return "Data [id=" + id + ", value=" + value + "]"; } public static Data fromMap(Map properties) { Data data = new Data(); data.setId(new Integer(properties.get("id"))); data.setValue(properties.get("value")); return data; } } 

以上程序打印:

 Data [id=2, value=some other thing] Data [id=1, value=something] 

因为此json对象使用int作为字段键,所以在反序列化时不能指定字段键名。 因此,我需要首先从集合中提取值集:

 JsonParser parser = new JsonParser(); JsonObject obj = parser.parse(json).getAsJsonObject(); Set> set = obj.entrySet(); 

现在“set”包含一组,在我的例子中是<1,{id:1,value:something}>。

因为这里的密钥没用,所以我只需要设置值,所以我迭代集合来提取值集。

 for (Entry j : set) { JsonObject value = (JsonObject) j.getValue(); System.out.println(value.get("id")); System.out.println(value.get("value")); } 

如果你有更复杂的结构,比如嵌套的json对象,你可以这样:

 for (Entry j : locations) { JsonObject location = (JsonObject) j.getValue(); JsonObject coordinate = (JsonObject) location.get("coordinates"); JsonObject address = (JsonObject) location.get("address"); System.out.println(location.get("location_id")); System.out.println(location.get("store_name")); System.out.println(coordinate.get("latitude")); System.out.println(coordinate.get("longitude")); System.out.println(address.get("street_number")); System.out.println(address.get("street_name")); System.out.println(address.get("suburb")); } 

希望能帮助到你。