@Tim Mac 的响应是正确的,但是您可以通过为您的课程编写自定义反序列化器来使其更加优雅。MyEntity
它应该是这样的:
private class MyEntityDeserializer implements JsonDeserializer<MyEntity> {
public MyEntity deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
throws JsonParseException {
JsonObject rootObj = json.getAsJsonObject();
String nid = rootObj
.get("nid")
.getAsJsonArray()
.get(0)
.getAsJsonObject()
.get("value")
.getAsString();
String uuid = rootObj
.get("uuid")
.getAsJsonArray()
.get(0)
.getAsJsonObject()
.get("value")
.getAsString();
MyEntity entity = new MyEntity(nid, uuid);
return entity;
}
}
然后你必须注册TypeAdapter
:
Gson gson = new GsonBuilder().registerTypeAdapter(MyEntity.class, new MyEntityDeserializer()).create();
最后你只需要像往常一样解析你的 JSON,使用:
MyEntity entity = gson.fromJson(yourJsonString, MyEntity.class);
Gson 将自动使用您的自定义反序列化器将您的 JSON 解析到您的MyEntity
类中。