dReAmEr
dReAmEr

Reputation: 7196

How to customize a specific date field in JSON using GSON API in Java?

I have a JSON structure like below.

{
"email":"[email protected]",
"mobile":9911776556,
"customerLanguage":"English",
"sms_flag":1,
"ivr_flag":0,
"dateOfBirth":"19-11-1981",
"dateOfJoining":"08-10-2001"
}

Now i want to customize only dateOfBirth field, i have tried below but it changes both dateOfBirth and dateOfJoining.

Gson jsonConvertor = new GsonBuilder().setDateFormat("dd/mm/yyyy").create();
TestJson userAuthenticationDTO = jsonConvertor.fromJson(request_body, TestJson.class);

My TestJson class has below structure.

TestJson -->

class TestJson{

   Date dateOfBirth;

   Date dateOfJoining;

  // other fields.....

}

TestJson object contains both date field modified ,i want only one to be modified?

Upvotes: 0

Views: 1024

Answers (2)

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 279970

The clean way to do this with gson is to write and register your own TypeAdapter which serializes your TestJson type in an appropriate manner, ie. one Date field one way and the other Date field in another.

This

Gson jsonConvertor = new GsonBuilder().setDateFormat("dd/mm/yyyy").create();

sets the formatting for any and all Date values.

Upvotes: 3

Ankur Singhal
Ankur Singhal

Reputation: 26077

Seems like you need to play around with keys.

First Approach can be to deserialize into a java.util.Map, and then just modify the Java Map as wanted.

or something as below

JSONObject object=new JSONObject(myJsonString);
JSONObject childobject=object.getJSONObject("dateOfJoining");

JSONObject modifiedjson=new JSONObject();
modifiedjson.put("value", formatedValue()); 

Upvotes: 1

Related Questions