MongoDB "NumberLong/$numberLong" issue while converting back to Java Object

Geek picture Geek · Mar 2, 2017 · Viewed 9.8k times · Source

I am having a json which is somethink like {"Header" : {"name" : "TestData", "contactNumber" : 8019071740}}

If i insert this to mongoDB it will be something like

{"_id" : ObjectId("58b7e55097989619e4ddb0bb"),"Header" : {"name" : "TestData","contactNumber" : NumberLong(8019071743)}

When i read this data back and try to convert to java object using Gson it throws exception com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected a long but was BEGIN_OBJECT at line 1 column 109 path $.Header.contactNumber

I have found this, But i was wondering if i have very complex json structure then i might need to manipulate many json nodes in this approach.

Do anyone has any better alternatives on this.

Edit:1 I am reading querying and converting json as below

Document MongoDocument = mycollection.find(searchCondition);
String resultJson =  MongoDocument.toJson();
Gson gson = new Gson();
Model model= gson.fromJson(resultJson, ItemList.class);

Answer

Deepak Gusain picture Deepak Gusain · Aug 21, 2019

We can use below code:

Document doc = documentCursor.next();
JsonWriterSettings relaxed = JsonWriterSettings.builder().outputMode(JsonMode.RELAXED).build();
CustomeObject obj = gson.fromJson(doc.toJson(relaxed), CustomeObject.class);