0

I'm using Gson to serialize my javabean in a JSON, and I'm having problems with Date type fields.

If I create GsonBuilder without any redefinition

Gson gson = new GsonBuilder().create();

it generates the Date field in JSON in the format "Jan 6, 2017 12:00:00 AM", but with the data type String.

If I set the builder to a date format

Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create();

It generates the field in the desired format, but remains as String.

With the String type, I can't do query based on periods (like this). Manually changing one of the records, I was able to get response:

before:
{"_id" : ObjectId("586fa17851ba381278b059ac"),
"start" : "2017-01-06"),
...
}

after:
{"_id" : ObjectId("586fa17851ba381278b059ac"),
"start" : ISODate("2017-01-06T12:00:00.000Z"),
...
}

How can I ensure the generation of a Date field using Gson?

Community
  • 1
  • 1
Rogério Arantes
  • 712
  • 1
  • 8
  • 29
  • I don't think you can generate mongodb compatiable json from Gson. Would you consider using BSON ? http://mongodb.github.io/mongo-java-driver/3.2/bson/extended-json/#mongodb-extended-json – s7vr Jan 06 '17 at 18:38
  • Thanks for your comment, I will check how much I will have to change to adopt the BSON. If you prefer, enter your comment as an answer. – Rogério Arantes Jan 09 '17 at 16:06

1 Answers1

1

Don't think you can generate Mongo db compatiable json from Gson.

BSON can help you with conversion. http://mongodb.github.io/mongo-java-driver/3.2/bson/extended-json/

You can also look into different Mongo Db object mapper libaries that will handle this part for you and more.

Some libraries include:

Morphia - http://mongodb.github.io/morphia/

Spring Mongo Db - http://projects.spring.io/spring-data-mongodb/

s7vr
  • 73,656
  • 11
  • 106
  • 127