Gson - 序列化时避免不必要的包装类

时间:2014-09-28 12:35:23

标签: java gson wrapper

我有一个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类和包装类。这可能+怎么样?

2 个答案:

答案 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);