我有一个看起来像这样的 json 响应:
{
"id":"001",
"name":"Name",
"param_distance":"10",
"param_sampling":"2"
}
我有两个类:Teste 和 Parameters
public class Test {
private int id;
private String name;
private Parameters params;
}
public class Parameters {
private double distance;
private int sampling;
}
我的问题是:有没有办法让 Gson 明白一些 json 属性应该转到 Parameters 类,或者唯一的方法是“手动”解析这个?
编辑
好吧,只是为了让我在@MikO 的回答中的评论更具可读性:
我将在 json 输出中添加一个对象列表,因此 json 响应应如下所示:
{
"id":"001",
"name":"Name",
"param_distance":"10",
"param_sampling":"2",
"events":[
{
"id":"01",
"value":"22.5"
},
{
"id":"02",
"value":"31.0"
}
]
}
Deserializer 类看起来像这样:
public class TestDeserializer implements JsonDeserializer<Test> {
@Override
public Test deserialize(JsonElement json, Type type,
JsonDeserializationContext context) throws JsonParseException {
JsonObject obj = json.getAsJsonObject();
Test test = new Test();
test.setId(obj.get("id").getAsInt());
test.setName(obj.get("name").getAsString());
Parameters params = new Parameters();
params.setDistance(obj.get("param_distance").getAsDouble());
params.setSampling(obj.get("param_sampling").getAsInt());
test.setParameters(params);
Gson eventGson = new Gson();
Type eventsType = new TypeToken<List<Event>>(){}.getType();
List<Event> eventList = eventGson.fromJson(obj.get("events"), eventsType);
test.setEvents(eventList);
return test;
}
}
并做:
GsonBuilder gBuilder = new GsonBuilder();
gBuilder.registerTypeAdapter(Test.class, new TestDeserializer());
Gson gson = gBuilder.create();
Test test = gson.fromJson(reader, Test.class);
以我想要的方式给我测试对象。