如何在Android中使用Gson反序列化.NET JsonResult DateTime格式?

时间:2016-04-27 22:56:52

标签: android json gson

我以这种格式从服务器返回JSON:

{
    "StartDate": "/Date(1451593800000)/",
    "EndDate": "/Date(1483216200000)/"
}

在我的POJO中:

public class Data {
    java.util.Date startDate;
    java.util.Date endDate;
}

我的Gson对象:

private final Gson gson =  new GsonBuilder()
    .serializeNulls()
    .setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE)
    .create();

当我想解析这个JSON时,我得到了这个错误:

Unparseable date: "/Date(1483216200000)/" (at offset 0)

使用Gson在Android中解析此类JSON的正确方法是什么?

1 个答案:

答案 0 :(得分:1)

我做过这样的事情,创建一个Date Serializer并将其注册到GsonBuilder。

import java.lang.reflect.Type;
import java.util.Date;

import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;

public class DateDeserializer implements JsonDeserializer<Date> {

    @Override
    public Date deserialize(JsonElement element, Type arg1,
            JsonDeserializationContext arg2) throws JsonParseException {
        String data = element.getAsString();
        data = data.replace("/Date(", "");
        data = data.replace(")/", "");
        try {
            return new Date(Long.parseLong(data));
        } catch (Exception e) {
            System.out.println("Failed to parse Date due to:");
            return null;
        }
    }
}

注册Gson Builder

Gson gson = new GsonBuilder().serializeNulls()
            .setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE)
            .registerTypeAdapter(Date.class, new DateDeserializer()).create();