使用Gson将单个json条目解析为多个对象

时间:2013-07-16 14:59:12

标签: java json parsing gson

我有一个json响应,如下所示:

{
    "id":"001",
    "name":"Name",
    "param_distance":"10",
    "param_sampling":"2"
}

我有两个类:Teste和参数

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

以我想要的方式给我测试对象。

1 个答案:

答案 0 :(得分:3)

让Gson理解它的方法是通过为TypeAdapter类创建Test来编写自定义反序列化器。您可以在Gson's User Guide中找到相关信息。它不完全是手动解析,但它并没有那么不同,因为你必须告诉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类。