我需要反序列化json,它是日期/长值的数组。这是返回的JSON的示例:

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

使用GSON,我可以将其反序列化为List<Map<Date,String>>,但是希望能够将其转换为类似于List<MyCustomClass>的代码:
public class MyCustomClass() {
    Date date;
    Long value;
}

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

最佳答案

您需要编写一个自定义解串器。您还需要使用 SimpleDateFormat 可以实际解析的时区格式。 zZ都不匹配-07:00,后者是RFC 822时区格式(-0700)或“一般时区”(Mountain Standard TimeMSTGMT-07:00)的怪异混合。或者,您可以坚持使用完全相同的时区格式和use JodaTime's DateTimeFormat

MyCustomClass.java

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

上面所有代码都是on Github,可以随时克隆(尽管您还将获得用于回答其他问题的代码)。

关于java - GSON将键值反序列化到自定义对象,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/5845822/

10-12 00:11
查看更多