0

I have a jsonstring as below

{"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}]}

I need to convert this string to CoaAccountList class object.Below is the CoaAccountList class. 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;
}

}

Where COAAccount class containing transDate as TimeStamp variable and in json string its as Long variable, so my convertion process results a com.google.gson.JsonSyntaxException for this long transDate value.Below is the code i used to convert the json string to CoaAccountList

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

Below is the COAAccount class.

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

Please help me to convert this json string to CoaAccountList object.

KJEjava48
  • 1,967
  • 7
  • 40
  • 69
  • tried converting it "manually" via a setTransDate(long) method / a constructor that accepts long for transDate? – ceekay May 13 '15 at 10:12
  • quite similar question: http://stackoverflow.com/questions/22841306/com-google-gson-jsonsyntaxexception-when-trying-to-parse-date-time-in-json – ceekay May 13 '15 at 10:21

3 Answers3

2

In the case where custom deserialization pattern needs to be used Gson allows you to register your own deserialization code as appropriate per type.

To do this, you'll first need to instantiate Gson from a GsonBuilder instead under the following code:

GsonBuilder gson = new GsonBuilder();

then you'll need to attach a JsonDeserializer instance into GsonBuilder when dealing with the type Timestamp as follows:

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

Note: GsonTimestampDeserializer is a custom class we're creating below, you can technically name it anything you want.

Registering a custom deserializer, Gson will automatically invoke the deserialize() method from the JsonDeserializer interface as needed when it needs to convert from a raw type (int, string, double, etc) into the specified registered type. To take advantage of this, we implement the deserializer as below:

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

N.B: I'm assuming you're using the Timestamp object from java.sql that provides a constructor that takes a long.

Putting it all together:

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

As Gson parses the JSON string and attempts to fill in corresponding values, it encounters the Timestamp type on transDate and rather than using the default Object deserialization scheme java has, uses the custom deserialization scheme we provide to convert the long into a Timestamp object.

The approach can be generalized to all sorts of complex container classes that can store their data as a single primitive type, and equivalently a GsonSerializer can be used to achieve the reverse.

initramfs
  • 8,275
  • 2
  • 36
  • 58
1

You need to create a custom deserialize method to parse the Timestamp.

E.g. :

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);
Sachin Gupta
  • 7,805
  • 4
  • 30
  • 45
0

You need to register Json deserializer for Data.class in your builder. Original answer 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());
        }
    });
Community
  • 1
  • 1
SanyaLuc
  • 116
  • 5