【问题标题】:How to deserialize class containing arraylist with timestamp data如何反序列化包含带有时间戳数据的arraylist的类
【发布时间】:2015-07-24 13:21:13
【问题描述】:

我有一个jsonstring如下

{"coaList":[{"iD":324,"strName":"Cash","hasChildren":false,"amount":3500.0,"transDate":1421346600000},{"iD":326,"strName":"Cash","hasChildren":false,"amount":2000.0,"transDate":1421346600000},{"iD":328,"strName":"HDFC Bank","hasChildren":false,"amount":2500.0,"transDate":1421346600000}]}

我需要将此字符串转换为 CoaAccountList 类对象。下面是 CoaAccountList 类。 CoaAccountList.java:

public class CoaAccountList implements Serializable  {

private List<COAAccount> coaList;

public List<COAAccount> getCoaList() {
    return coaList;
}

public void setCoaList(List<COAAccount> coaList) {
    this.coaList = coaList;
}

}

其中 COAAccount 类包含 transDate 作为 TimeStamp 变量,在 json 字符串中作为 Long 变量,所以我的转换过程导致这个长 transDate 值的 com.google.gson.JsonSyntaxException。下面是我用来转换 json 字符串的代码到 CoaAccountList

Gson gson = new Gson();
CoaAccountList transHisList=gson.fromJson(jsonString, CoaAccountList.class);

下面是 COAAccount 类。

COAAccount.java:

public class COAAccount implements Serializable {
private int iD;
private String strName;
private boolean hasChildren;
private float amount;
private Timestamp transDate;

public COAAccount() {
    super();
    // TODO Auto-generated constructor stub
}

public COAAccount(int iD, String strName, boolean hasChildren, float amount, Timestamp transDate) {
    super();
    this.iD = iD;
    this.strName = strName;
    this.hasChildren = hasChildren;
    this.amount = amount;
    this.transDate = transDate;
}

public int getiD() {
    return iD;
}

public void setiD(int iD) {
    this.iD = iD;
}

public String getStrName() {
    return strName;
}

public void setStrName(String strName) {
    this.strName = strName;
}

public boolean isHasChildren() {
    return hasChildren;
}

public void setHasChildren(boolean hasChildren) {
    this.hasChildren = hasChildren;
}

public float getAmount() {
    return amount;
}

public void setAmount(float amount) {
    this.amount = amount;
}

public Timestamp getTransDate() {
    return transDate;
}

public void setTransDate(Timestamp transDate) {
    this.transDate = transDate;
}

@Override
public String toString() {
    return strName;
}
}

请帮我将此 json 字符串转换为 CoaAccountList 对象。

【问题讨论】:

标签: java json gson


【解决方案1】:

在需要使用自定义反序列化模式的情况下,Gson 允许您根据类型注册自己的反序列化代码。

为此,您首先需要在以下代码下从 GsonBuilder 实例化 Gson:

GsonBuilder gson = new GsonBuilder();

那么在处理Timestamp 类型时,您需要将JsonDeserializer 实例附加到GsonBuilder,如下所示:

gson.registerTypeAdapter(Timestamp.class, new GsonTimestampDeserializer());

注意:GsonTimestampDeserializer 是我们在下面创建的自定义类,从技术上讲,您可以随意命名。

注册自定义反序列化器,当Gson需要将原始类型(int、string、double等)转换为指定的注册类型时,会根据需要自动从JsonDeserializer接口调用deserialize()方法。为了利用这一点,我们实现了如下的反序列化器:

private class GsonTimestampDeserializer implements JsonDeserializer<Timestamp>{
    public Timestamp deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException{
        return new Timestamp(json.getAsJsonPrimitive().getAsLong());
    }
}

注意:我假设您正在使用 java.sql 中的 Timestamp 对象,该对象提供了一个需要很长时间的构造函数。

把它们放在一起:

GsonBuilder gson = new GsonBuilder();
gson.registerTypeAdapter(Timestamp.class, new GsonTimestampDeserializer());

private class GsonTimestampDeserializer implements JsonDeserializer<Timestamp>{
    public Timestamp deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException{
        return new Timestamp(json.getAsLong());
    }
}

Gson gsonInstance = gson.create();

CoaAccountList transHisList = gsonInstance.fromJson(jsonString, CoaAccountList.class);

当 Gson 解析 JSON 字符串并尝试填写相应的值时,它在 transDate 上遇到 Timestamp 类型,而不是使用 java 具有的默认 Object 反序列化方案,而是使用我们提供的自定义反序列化方案将 long 转换为时间戳对象。

该方法可以推广到各种复杂的容器类,这些容器类可以将其数据存储为单个原始类型,等效地,可以使用 GsonSerializer 来实现相反的效果。

【讨论】:

    【解决方案2】:

    您需要在构建器中为 Data.class 注册 Json 反序列化器。原答案here

    // Creates the json object which will manage the information received
        GsonBuilder builder = new GsonBuilder();
    
        // Register an adapter to manage the date types as long values
        builder.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {
            public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
                return new Date(json.getAsJsonPrimitive().getAsLong());
            }
        });
    

    【讨论】:

      【解决方案3】:

      您需要创建一个自定义的反序列化方法来解析时间戳。

      例如:

      GsonBuilder builder = new GsonBuilder();
      
      builder.registerTypeAdapter(Timestamp.class, new JsonDeserializer<Timestamp>() {
      
      @Override
      public Timestamp deserialize(JsonElement json, Type type, JsonDeserializationContext deserializationContext) throws JsonParseException {
          return new Timestamp(json.getAsJsonPrimitive().getAsLong());
          }
      });
      
      Gson gson = builder.create();
      CoaAccountList transHisList = gson.fromJson(jsonString, CoaAccountList.class);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-06-14
        • 2014-05-24
        • 1970-01-01
        • 2011-01-07
        • 2014-01-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多