Reputation: 484
I have a REST
service which consumes "test/plain", basically the string I receive is a JSON
string, I have the following code to parse the JSON
string to DBObject
so that I can save it to MongoDB
.
@Timed
@POST
@Consumes("text/plain")
@Produces(MediaType.APPLICATION_JSON)
public Response insertscreenview(String message) {
// System.out.println(message);
final Logger logger = LoggerFactory.getLogger(ScreenviewResource.class);
logger.info("Screenview Insert Request Recieved" + "\n" + message);
screenviewInstance = new Screenview();
tracInfoInstance = new TracInfo();
BasicDBObject ageRangeId;
GeoCheckManager geoCheckInstance = new GeoCheckManager();
boolean brCheck;
try {
ObjectMapper mapper = new ObjectMapper();
JsonNode actualObj = mapper.readTree(message);
System.out.println(message);
DBObject objInstance = (DBObject)JSON.parse(message);
...}
My JSON
string look's as follow
{
"Screenview": {
"TracInfo": null,
"Id": 0,
"ScreenName": "SettingsActivity",
"Timestamp": "2014-07-02T18:50:10",
"Timezone": "Asia/Kolkata",
"ApplicationId": null,
"DeviceId": null,
"UserId": null,
"SessionId": "5684ae84-9a48-49a5-ab47-fcb7de3c08cf"
},
"Session": {
"Id": "5684ae84-9a48-49a5-ab47-fcb7de3c08cf",
"StartTime": "2014-07-02T13:20:58",
"EndTime": "2014-07-02T13:21:09",
"EntryScreen": "AccessPointActivity",
"ExitScreen": "SettingsActivity",
"FirstEvent": "SCREEN STARTED",
"LastEvent": "SCREEN STOPPED",
"ApplicationId": "fa41f204bfc711e3b9f9c8cbb8c502c4",
"DeviceId": "0_6e505bcbe7e511e393b60aba4a7caa0b",
"UserId": "",
"TracInfoId": -1,
"SensorsInfo": null
},
"CustomParams": {
"Latitude": 0,
"Longitude": 0,
"Country": null,
"CountryCode": null,
"Region": null,
"RegionCode": null,
"City": null,
"Gender": null,
"Age": 0,
"Platform": "Android",
"OSVersion": "16",
"Manufacturer": "samsung",
"Resolution": "600 * 976",
"NetworkCarrier": null,
"Timezone": null
} }
It gives me error as follow and I am unable to find why.
java.lang.ClassCastException: java.util.HashMap cannot be cast to com.mongodb.DBObject
Upvotes: 5
Views: 7579
Reputation: 8059
More up to date way of parsing a string to a DBObject:
BasicDBObject dbObject = com.mongodb.BasicDBObject.parse(rawJsonString)
Note that this should probably only be used for free schemas json objects, most of the time something like Springs MongoDBTemplate/MongoRepository etc. can be used to take care of the mapping.
Upvotes: 2
Reputation: 19700
Instead of using DBObject
, you could make use of BasicDBObject
which has a constructor taking Map as input:
BasicDBObject obj= new BasicDBObject(JSON.parse(message));
or using ObjectMapper:
BasicDBObject obj = mapper.readValue(message, BasicDBObject.class);
Upvotes: 3