我正在使用的服务器返回一个json对象,该对象包含一个对象列表,而不仅仅是一个.
{
"1":{"id":"1","value":"something"},
"2":{"id":"2","value":"some other thing"}
}
Run Code Online (Sandbox Code Playgroud)
我想将此json对象转换为对象数组.
我知道我可以使用Gson,并创建一个这样的类:
public class Data {
int id;
String value;
}
Run Code Online (Sandbox Code Playgroud)
然后使用
Data data = new Gson().fromJson(response, Data.class);
Run Code Online (Sandbox Code Playgroud)
但它仅适用于json对象内的对象. 我不知道如何将带有数字的json对象转换为键.
或者我需要改变服务器以响应这样的事情?:
{["id":"1","value":"something"],["id":"2","value":"some other thing"]}
Run Code Online (Sandbox Code Playgroud)
但我不想更改为服务器,因为我必须更改所有客户端代码.
因为这个json对象使用int作为字段键,所以反序列化时不能指定字段键名称。因此我需要首先从集合中提取值集:
JsonParser parser = new JsonParser();
JsonObject obj = parser.parse(json).getAsJsonObject();
Set<Entry<String,JsonElement>> set = obj.entrySet();
Run Code Online (Sandbox Code Playgroud)
现在“set”包含一组 ,在我的例子中是 <1,{id:1,value:something}> 。
因为键在这里没用,我只需要值集,所以我迭代该集来提取值集。
for (Entry<String,JsonElement> j : set) {
JsonObject value = (JsonObject) j.getValue();
System.out.println(value.get("id"));
System.out.println(value.get("value"));
}
Run Code Online (Sandbox Code Playgroud)
如果你有更复杂的结构,比如嵌套的 json 对象,你可以有这样的东西:
for (Entry<String,JsonElement> 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"));
}
Run Code Online (Sandbox Code Playgroud)
希望能帮助到你。