我有一个Json字符串:
{
"Locations":{
"Location":[{
"elevation":"100",
"latitude":"0",
"longitude":"0",
"name":"Ocean"
},
...
]}
}
我想使用Location
将其序列化为Gson
个数组:
public class Location {
public double elevation;
public double latitude;
public double longitude;
public String name;
}
而不是使用Locations
字段创建Locations
类和包装类。这可能+怎么样?
答案 0 :(得分:1)
这应该有效:
jsonStr = "...";
Class<? extends HashMap> mapType = new HashMap<String, Object>().getClass();
Map data = new Gson().fromJson(job.jobContext, mapType);
JsonObject locations = data.get("Locations").getAsJsonObject();
JsonArray locationAry = locations.get("Location").getAsJsonArray();
for(JsonElement jsonEle: locationAry) {
Location loc = new Location();
JsonObject jsLoc = jsonEle.getAsJsonObject();
loc.elevation = jsLoc.get("elevation").getAsInt();
// ...
}
答案 1 :(得分:1)
您可以获取Locaitons
对象,然后获取Location
数组。下面的代码是纯Gson:
String jsonAsText = "{\"Locations\":{\"Location\":[{\"elevation\":\"100\",\"latitude\":\"0\",\"longitude\":\"0\",\"name\":\"Ocean\"},{\"elevation\":\"100\",\"latitude\":\"0\",\"longitude\":\"0\",\"name\":\"Ocean\"}]}}";
GsonBuilder gsonBuilder = new GsonBuilder();
Gson gson = gsonBuilder.create();
java.lang.reflect.Type listType = new com.google.gson.reflect.TypeToken<List<Location>>(){}.getType();
JsonArray locationJsonList = (JsonArray) ((JsonObject) gson.fromJson(jsonAsText, JsonObject.class).get("Locations")).get("Location");
List<Location> locatioList = gson.fromJson(locationJsonList, listType);