GSON 将键值反序列化为自定义对象 [英] GSON deserializing key-value to custom object

查看:32
本文介绍了GSON 将键值反序列化为自定义对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要反序列化 json,它是一个日期/长值数组.以下是返回的 JSON 示例:

I need to deserialize json which is an array of date/long values. Here is an example of the returned JSON:

[{"2011-04-30T00:00:00-07:00":100}, {"2011-04-29T00:00:00-07:00":200}]

使用 GSON 我可以将其反序列化为 List>,但希望能够将其转换为 List 类似于:

Using GSON I am able to deserialize this to a List<Map<Date,String>>, but would like to be able to convert it to a List<MyCustomClass> similar to:

public class MyCustomClass() { 
    Date date;
    Long value;
}

我似乎找不到一种方法来指示 GSON 将 JSON 映射的键/值映射到我的自定义类中的日期/值字段.有没有办法做到这一点,或者地图列表是唯一的路线?

I cannot seem to find a way to instruct GSON to map the key/value of the JSON map to the date/value fields in my custom class. Is there a way to do this, or is a list of maps the only route?

推荐答案

你需要编写一个自定义的解串器.您还需要使用 的时区格式SimpleDateFormat 实际上可以解析.zZ 都不会匹配 -07:00,这是 RFC 822 时区格式(-0700) 或一般时区"(Mountain Standard TimeMSTGMT-07:00).或者,您可以坚持使用完全相同的时区格式,并且 使用 JodaTime 的 DateTimeFormat.

You need to write a custom deserializer. You also need to use a time zone format that SimpleDateFormat can actually parse. Neither z nor Z will match -07:00, which is a weird mix of RFC 822 time zone format (-0700) or a "general time zone" (Mountain Standard Time or MST or GMT-07:00). Alternately, you can stick with the exact same time zone format, and use JodaTime's DateTimeFormat.

public class MyCustomClass
{
    Date date;
    Long value;

    public MyCustomClass (Date date, Long value)
    {
        this.date = date;
        this.value = value;
    }

    @Override
    public String toString()
    {
        return "{date: " + date + ", value: " + value + "}";
    }
}

MyCustomDeserializer.java

public class MyCustomDeserializer implements JsonDeserializer<MyCustomClass>
{
    private DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssz");

    @Override
    public MyCustomClass deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext ctx) throws JsonParseException
    {
        JsonObject obj = json.getAsJsonObject();
        Entry<String, JsonElement> entry = obj.entrySet().iterator().next();
        if (entry == null) return null;
        Date date;
        try
        {
            date = df.parse(entry.getKey());
        }
        catch (ParseException e)
        {
            e.printStackTrace();
            date = null;
        }
        Long value = entry.getValue().getAsLong();
        return new MyCustomClass(date, value);
    }
}

GsonTest.java

public class GsonTest
{
    public static void main(String[] args)
    {
        // Note the time zone format tweak (removed the ':')
        String json = "[{"2011-04-30T00:00:00-0700":100}, {"2011-04-29T00:00:00-0700":200}]";

        Gson gson =
            new GsonBuilder()
            .registerTypeAdapter(MyCustomClass.class, new MyCustomDeserializer())
            .create();
        Type collectionType = new TypeToken<Collection<MyCustomClass>>(){}.getType();
        Collection<MyCustomClass> myCustomClasses = gson.fromJson(json, collectionType);
        System.out.println(myCustomClasses);
    }
}

以上所有代码在Github上,请随意克隆(尽管您也会获得用于回答其他问题的代码).

All of the above code is on Github, feel free to clone (though you'll get code for answers to other questions as well).

这篇关于GSON 将键值反序列化为自定义对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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