laaptu
laaptu

Reputation: 2973

Gson is it possible to modify the parsed data while mapping on the given Class

I have a following JsonArray file

 [
  {
    "DateSent": "06/22/2014 11:09:11",
    "UserName": "santosh"
  }
]

And I am mapping it to the following AssistResponse class

public class AssistResponse {

@SerializedName("DateSent")
private String dateSent;
@SerializedName("UserName")
public String userName;

public void setDateSent(String dateSent) {
    this.dateSent = dateSent;
    System.out.println(this.dateSent);
}

public String getDateSent() {
    return this.dateSent;
}

}

I can easily get List or Array of this class.But I do want to modify the dateSent property of classAssistResponse while Gson maps the class. Meaning Gson, do parse the Jsonfile, then assigns the value to the @SerializedName.So while assigning the value, I need to change the dateSent value. The dateSent contains the server date value,but I want to change it to the local time. I can use the parsed List and then iterate it and get dateSent value and then change it. But, is it possible to change the value, during the parsing of Json by Gson, so that at the end I don't have to again iterate the whole Array

Thanks

Upvotes: 1

Views: 2312

Answers (2)

Braj
Braj

Reputation: 46871

You need JsonDeserializer where you can change the date into local date as per your need from the JSON string and set the value in your custom POJO class as shown below.

For more info have a look at GSON Deserialiser Example

I have already posted it here and here in the same context that might help you to make it more clear.


You can use Date as data type for dateSent or leave it as it is if you don't want to change.

Sample code:

class AssistResponse {

    @SerializedName("DateSent")
    private Date dateSent;
    @SerializedName("UserName")
    public String userName;
    // getter & setter
}


class AssistResponseDeserializer implements JsonDeserializer<AssistResponse> {

    @Override
    public AssistResponse deserialize(final JsonElement json, final Type typeOfT,
            final JsonDeserializationContext context) throws JsonParseException {

        JsonArray jsonArray = json.getAsJsonArray();
        JsonElement jsonElement = jsonArray.get(0);
        JsonObject jsonObject = (JsonObject) jsonElement;

        AssistResponse assistResponse = new AssistResponse();
        assistResponse.setUserName(jsonObject.get("UserName").getAsString());

        SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
        String dateString = jsonObject.get("DateSent").getAsString();
        try {
            Date date = dateFormat.parse(dateString);
            Date localDate=...              // <== here change it to local date
            assistResponse.setDateSent(localDate);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        return assistResponse;
    }
}
AssistResponse data = new GsonBuilder()
        .registerTypeAdapter(AssistResponse.class, new AssistResponseDeserializer())
        .create().fromJson(jsonString, AssistResponse.class);

System.out.println(new GsonBuilder().setPrettyPrinting().create().toJson(data));

Upvotes: 2

Yadu Krishnan
Yadu Krishnan

Reputation: 3522

private String dateSent;

Does dateSent needs to be a string? Why can't you keep it as Date ?

I think you can write a gson deserializer for this. You can modify the date in the deserializer and returned the modified date.

JsonDeserializer<Date> deser = new JsonDeserializer<Date>() {
  @Override
  public Date deserialize(JsonElement json, Type typeOfT,
       JsonDeserializationContext context) throws JsonParseException {
           Date newDate = //TODO: modifications;
           return newDate;

  }
};

Upvotes: 0

Related Questions