我如何为Gson编写定制的JSON解串器? [英] How do I write a custom JSON deserializer for Gson?

查看:102
本文介绍了我如何为Gson编写定制的JSON解串器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Java类,用户:

  public class User 
{
int id;
字符串名称;
时间戳updateDate;
}

我收到一个包含来自webservice的用户对象的JSON列表:

  [{id:1,name:Jonas,update_date:1300962900226},
{id:5,name:Test,date_date:1304782298024}]



  @Override 
public User反序列化(JsonElement json,Type类型,
JsonDeserializationContext上下文)throws JsonParseException {

返回新用户(
json.getAsJsonPrimitive()。getAsInt(),
json.getAsString(),
json.getAsInt(),
(Timestamp)context.deserialize(json.getAsJsonPrimitive(),
Timestamp.class));
}

但是我的反序列化器不起作用。我怎样才能为Gson编写一个自定义的JSON解串器?

解决方案

  @Override 
public public deserialize(JsonElement json,Type type,
JsonDeserializationContext context)throws JsonParseException {

JsonObject jobject = json.getAsJsonObject();

返回新用户(
jobject.get(id)。getAsInt(),
jobject.get(name)。getAsString(),
新的时间戳(jobject.get(update_date)。getAsLong()));
}

我假设User类具有适当的构造函数。


I have a Java class, User:

public class User
{
    int id;
    String name;
    Timestamp updateDate;
}

And I receive a JSON list containing user objects from a webservice:

[{"id":1,"name":"Jonas","update_date":"1300962900226"},
{"id":5,"name":"Test","date_date":"1304782298024"}]

I have tried to write a custom deserializer:

@Override
public User deserialize(JsonElement json, Type type,
                        JsonDeserializationContext context) throws JsonParseException {

        return new User(
            json.getAsJsonPrimitive().getAsInt(),
            json.getAsString(),
            json.getAsInt(),
            (Timestamp)context.deserialize(json.getAsJsonPrimitive(),
            Timestamp.class));
}

But my deserializer doesn't work. How can I write a custom JSON deserializer for Gson?

解决方案

@Override
public User deserialize(JsonElement json, Type type,
        JsonDeserializationContext context) throws JsonParseException {

    JsonObject jobject = json.getAsJsonObject();

    return new User(
            jobject.get("id").getAsInt(), 
            jobject.get("name").getAsString(), 
            new Timestamp(jobject.get("update_date").getAsLong()));
}

I'm assuming User class has the appropriate constructor.

这篇关于我如何为Gson编写定制的JSON解串器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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