用Gson解析单个json条目到多个对象 [英] Parsing single json entry to multiple objects with Gson

查看:652
本文介绍了用Gson解析单个json条目到多个对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我有两个类:Teste和Parameters

  public class Test {
private int id;
私人字符串名称;
private参数params;
}

public class Parameters {
private double distance;
private int sampling;

$ / code>

我的问题是:有没有办法让Gson明白一些json属性应该去参数类,或者唯一的方法是手动解析这个?



编辑



好吧,只是为了让我在@MyO的回答中的评论更具可读性:



我将一个对象列表添加到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实现了JsonDeserializer< Test> {
@Override
public Test反序列化(JsonElement json,Type类型,
JsonDeserializationContext上下文)throws JsonParseException {

JsonObject obj = json.getAsJsonObject();

Test test = new Test();
test.setId(obj.get(id)。getAsInt());
test.setName(obj.get(name)。getAsString());

参数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();
列表< Event> eventList = eventGson.fromJson(obj.get(events),eventsType);
test.setEvents(eventList);
return test;


code $

$ b

并做:

  GsonBuilder gBuilder = new GsonBuilder(); 
gBuilder.registerTypeAdapter(Test.class,new TestDeserializer());
Gson gson = gBuilder.create();
Test test = gson.fromJson(reader,Test.class);

以我想要的方式为我提供测试对象。

解决方案

使Gson明白它的方法是通过创建 TypeAdapter来编写自定义反序列化程序为你的 Test 类。您可以在 Gson用户指南 。它不完全是一个手动解析,但它没有什么不同,因为你必须告诉Gson如何处理每个JSON值......



它应该是这样的:

  private class TestDeserializer实现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();

//假设你有合适的构造函数...
Test test = new Test(id,name,new Parameters(distance,sampling));

return test;


然后你必须注册 TypeAdapter with:

  GsonBuilder gson = new GsonBuilder(); 
gson.registerTypeAdapter(Test.class,new TestDeserializer());

最后,您只需像往常一样解析JSON即可:

  gson.fromJson(yourJsonString,Test.class); 

Gson会自动使用您的自定义反序列化器将您的JSON解析到 Test class。


I have a json response that looks like this:

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

And I have two classes: Teste and Parameters

public class Test {
    private int id;
    private String name;
    private Parameters params;
}

public class Parameters {
    private double distance;
    private int sampling;
}

My question is: is there a way to make Gson understand that some of the json attributes should go to the Parameters class, or the only way is to "manually" parse this ?

EDIT

Well, just to make my comment in @MikO's answer more readable:

I'll add a list of an object to the json output, so json response should look like this:

  {
    "id":"001",
    "name":"Name",
    "param_distance":"10",
    "param_sampling":"2",
    "events":[
        {
            "id":"01",
            "value":"22.5"
        },
        {
            "id":"02",
            "value":"31.0"
        }
    ]
}

And the Deserializer class would look like this:

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

And doing:

GsonBuilder gBuilder = new GsonBuilder();
gBuilder.registerTypeAdapter(Test.class, new TestDeserializer());
Gson gson = gBuilder.create();
Test test = gson.fromJson(reader, Test.class);

Gives me the test object the way I wanted.

解决方案

The way to make Gson understand it is to write a custom deserializer by creating a TypeAdapter for your Test class. You can find information in Gson's User Guide. It is not exactly a manual parsing, but it is not that different, since you have to tell Gson how to deal with each JSON value...

It should be something like this:

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

Then you have to register the TypeAdapter with:

GsonBuilder gson = new GsonBuilder();
gson.registerTypeAdapter(Test.class, new TestDeserializer());

And finally you just have to parse your JSON as usual, with:

gson.fromJson(yourJsonString, Test.class);

Gson will automatically use your custom deserializer to parse your JSON into your Test class.

这篇关于用Gson解析单个json条目到多个对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆