使Gson理解它的方法是通过
TypeAdapter为您的
Test类创建一个自定义反序列化器。您可以在《
Gson用户指南》中 找到信息。它不完全是 手动解析 ,但没什么不同,因为您必须告诉Gson如何处理每个JSON值…
应该是这样的:
private class TestDeserializer implements JsonDeserializer<Test> { public Test deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { JsonObject obj = json.getAsJsonObject(); int id = obj.get("id").getAsInt(); String name = obj.get("name").getAsString(); double distance = obj.get("param_distance").getAsDouble(); int sampling = obj.get("param_sampling").getAsInt(); //assuming you have suitable constructors... Test test = new Test(id, name, new Parameters(distance, sampling)); return test; }}然后,您必须向注册
TypeAdapter:
GsonBuilder gson = new GsonBuilder();gson.registerTypeAdapter(Test.class, new TestDeserializer());
最后,您只需要照常解析JSON,即可:
gson.fromJson(yourJsonString, Test.class);
Gson将自动使用您的自定义反序列化器将JSON解析为您的
Test类。



