Parse Json to DBObject - java

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

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);

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.

Related

Cannot show null object in jsonobject

I have called a rest api from exsternal system using restTemplate. everything is work fine but when I get null in some of values (in example the footer value is null) it is always give jsonexception error
result api
{
"status": "success",
"data": {
"id": "22",
"organization_id": "33",
"name": "name_isf",
"language": "id",
"header": {
"format": "IMAGE",
"example": "#<Hashie::Mash header_handle=#<Hashie::Array [\"result_pic"]>>"
},
"body": "contenty for body",
"footer": null,
"buttons": [],
"status": "APPROVED",
"category": "PERSONAL_FINANCE_UPDATE"
}
}
every call api exsternal i always catch with jsonobject like below
JSONObject res2 = qontakService.getDetailTemplate();
then i will give that to the controller
JSONObject gabunganResult = new JSONObject();
gabunganResult.put("template", objectMapper.writeValueAsString(getDetail.get()));
gabunganResult.put("templateQontak", res2);
and the result error is
com.fasterxml.jackson.databind.JsonMappingException: Object is null (through reference chain: java.util.HashMap["details"]->net.sf.json.JSONObject["templateQontak"]->net.sf.json.JSONObject["data"]->net.sf.json.JSONObject["footer"]->net.sf.json.JSONNull["empty"])
how do I solve this problem ? thank you

Json Pagination not working from PageImpl

I have this controller:
#RequestMapping("/api")
public ResponseEntity<?> a(Pageable pageable) throws IOException {
ObjectMapper mapper = new ObjectMapper( );
File file = new File( "samplejson.json" );
JsonNode jsonNode = mapper.readTree( file );
List<JsonNode> nodes = new ArrayList<>();
if ( !jsonNode.isArray() )
nodes.add( jsonNode );
else
for ( JsonNode node : jsonNode )
nodes.add( node );
return new ResponseEntity<Object>( new PageImpl( nodes, pageable, nodes.size() ), HttpStatus.OK );
}
and when i postman it, it gives me this response:
{
"content": [
{
"id": 1,
"first_name": "Dode",
"email": "dcardall0#zimbio.com",
"gender": "Female",
"timestamp": "11/12/1981"
},
{
"id": 2,
"first_name": "Andrus",
"email": "amcgeever1#jigsy.com",
"gender": "Male",
"timestamp": "10/25/1988"
},
{
"id": 3,
"first_name": "Allyn",
"email": "afakes2#samsung.com",
"gender": "Male",
"timestamp": "9/3/1997"
},
{
"id": 4,
"first_name": "Merell",
"email": "mmoreton3#census.gov",
"gender": "Male",
"timestamp": "3/7/2009"
}
],
"last": true,
"totalElements": 10,
"totalPages": 1,
"size": 20,
"number": 0,
"sort": [
{
"direction": "DESC",
"property": "id",
"ignoreCase": false,
"nullHandling": "NATIVE",
"descending": true,
"ascending": false
}
],
"first": true,
"numberOfElements": 10 }
in the URI i have this
http://localhost:8080/api?sort=id, desc
However the pagination isn't working. As you can see, the sort direction in the response says "DESC". So it's supposed to be in descending order, right? But it's not working. I think because it's inside an object content which was created by pagination. But i don't know how to access what's inside content.
in order to apply PageRequest options like sort etc. you need to use PagingAndSortingRepository (see Spring Paging documentation)
So the sorting and getting the page is executed inside repository logic. See org.springframework.data.jpa.repository.support.SimpleJpaRepository.readPage
You can also go through this tutorial: https://www.petrikainulainen.net/programming/spring-framework/spring-data-jpa-tutorial-part-seven-pagination/

Convert a string from web service to JSON array

I want to convert this web service string to JSONArray , but it seems to have a problem , although I've validated it.
[
{
"hireDate": null,
"homePhoneNumber": null,
"gender": null,
"city": null,
"mobileNumber": null,
"idNumber": 123,
"religion": null,
"leftOver": 1,
"annualVacations": 5,
"dob": null,
"name": null,
"rank": 0,
"id": 1,
"workingHours": [],
"email": "ayman.daraghmah#exalt.ps",
"managers": [],
"alternativeMobileNumber": null,
"activated": true,
"username": "ayman.daraghmah#exalt.ps"
},
{
"hireDate": null,
"homePhoneNumber": null,
"gender": null,
"city": null,
"mobileNumber": null,
"idNumber": 123,
"religion": null,
"leftOver": 1,
"annualVacations": 5,
"dob": null,
"name": null,
"rank": 0,
"id": 11,
"workingHours": [],
"email": "aymandaraghmah#gmail.com",
"managers": [],
"alternativeMobileNumber": null,
"activated": true,
"username": "aymandaraghmah#gmail.com"
}
]
My Code:
JSONArray js = new JSONArray(payload);
what should the format of payload be to create the JSONArray ?
Looking at the code it looks like it should work. Following sample worked for me (The JSON is taken as a string for testing).
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class Main {
public static void main(String[] args) throws JSONException {
String test = "[{\"hireDate\": null,\"homePhoneNumber\": null,\"gender\": null,\"city\": null,\"mobileNumber\": null,\"idNumber\": 123,\"religion\": null,\"leftOver\": 1,\"annualVacations\": 5,\"dob\": null,\"name\": null,\"rank\": 0,\"id\": 1,\"workingHours\": [],\"email\": \"ayman.daraghmah#exalt.ps\",\"managers\": [],\"alternativeMobileNumber\": null,\"activated\": true,\"username\": \"ayman.daraghmah#exalt.ps\"},{\"hireDate\": null,\"homePhoneNumber\": null,\"gender\": null,\"city\": null,\"mobileNumber\": null,\"idNumber\": 123,\"religion\": null,\"leftOver\": 1,\"annualVacations\": 5,\"dob\": null,\"name\": null,\"rank\": 0,\"id\": 11,\"workingHours\": [],\"email\": \"aymandaraghmah#gmail.com\",\"managers\": [],\"alternativeMobileNumber\": null,\"activated\": true,\"username\": \"aymandaraghmah#gmail.com\"}]";
JSONArray jsonArray = new JSONArray(test);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject explrObject = jsonArray.getJSONObject(i);
System.out.println(explrObject.getString("username"));
}
}
}
I would recommend you to follow this link to get your problem solve.
http://www.java67.com/2016/10/3-ways-to-convert-string-to-json-object-in-java.html

how to parse json on java when theres no dictionary id?

I have this JSON result page, i want to parse it in .java
[
{
"kind": "track",
"id": 12429087,
"created_at": "2011/03/23 19:10:55 +0000",
"user_id": 2297976,
"duration": 473257,
"commentable": true,
"state": "finished",
"original_content_size": 19029935,
"sharing": "public",
"tag_list": "",
"permalink": "adikta-llega-la-calma-en-vivo",
"streamable": true,
"embeddable_by": "all",
"downloadable": true,
"purchase_url": null,
"label_id": null,
"purchase_title": null,
"genre": "",
"title": "ADIKTA - LLEGA LA CALMA en vivo 6",
"description": "",
"label_name": "",
"release": "",
"track_type": "",
"key_signature": "",
"isrc": "",
"video_url": null,
"bpm": null,
"release_year": null,
"release_month": null,
"release_day": null,
"original_format": "mp3",
"license": "all-rights-reserved",
"uri": "http://api.soundcloud.com/tracks/12429087",
"user": {
"id": 2297976,
"kind": "user",
"permalink": "adikta",
"username": "adikta",
"uri": "http://api.soundcloud.com/users/2297976",
"permalink_url": "http://soundcloud.com/adikta",
"avatar_url": "http://i1.sndcdn.com/avatars-000002155791-15emwj-large.jpg?3eddc42"
},
"permalink_url": "http://soundcloud.com/adikta/adikta-llega-la-calma-en-vivo",
"artwork_url": "http://i1.sndcdn.com/artworks-000005792200-72zfn4-large.jpg?3eddc42",
"waveform_url": "http://w1.sndcdn.com/hPYrb5G8V4an_m.png",
"stream_url": "http://api.soundcloud.com/tracks/12429087/stream",
"download_url": "http://api.soundcloud.com/tracks/12429087/download",
"playback_count": 114,
"download_count": 19,
"favoritings_count": 1,
"comment_count": 0,
"attachments_uri": "http://api.soundcloud.com/tracks/12429087/attachments"
},
this is my .java class (android) code:
try {
JSONObject respObj = new JSONObject(result);
JSONObject topTracksObj = respObj.getJSONObject("tracks");
JSONArray tracks = topTracksObj.getJSONArray("track");
for(int i=0; i<tracks.length(); i++) {
JSONObject track = tracks.getJSONObject(i);
String trackName = track.getString("permalink");
String trackUrl = track.getString("permalink_url");
JSONObject artistObj = track.getJSONObject("user");
String artistName = artistObj.getString("permalink");
String artistUrl = artistObj.getString("uri");
String imageUrl;....
But i cant find any solution to parse or navigate in this JSON directory without ids.
the api im using is soundcloud, but i cant find the answer there either. any help would be appreciated.
any suggestion?
thanks in advance
Kindly find the below mentioned code:
String str = "<YOUR_JSON_STRING>";
JSONArray jArrayObject;
try {
jArrayObject = new JSONArray(str);
for (int i = 0; i<jArrayObject.length(); i++) {
Log.d("kind==", jArrayObject.getJSONObject(i).getString("kind").toString());
Log.d("id==", jArrayObject.getJSONObject(i).getString("id").toString());
Log.d("created_at==", jArrayObject.getJSONObject(i).getString("created_at").toString());
JSONObject jObj = new JSONObject(jArrayObject.getJSONObject(i).getString("user").toString());
Log.d("id==", jObj.getString("id").toString());
Log.d("kind==", jObj.getString("kind").toString());
Log.d("permalink==", jObj.getString("permalink").toString());
Log.d("username==", jObj.getString("username").toString());
Log.d("permalink_url==", jObj.getString("permalink_url").toString());
Log.d("avatar_url==", jObj.getString("avatar_url").toString());
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

Parsing Facebook Graph API response

I'm working on Facebook Scores API for an android app. I query for the user score by accessing the user graph:
https://graph.facebook.com/user_id/scores&access_token={user_access_token}
I get a response like:
{
"data": [
{
"user": {
"name": "Michał Szydłowski",
"id": "100001699654797"
},
"score": 1200,
"application": {
"name": "QuizzlePeople",
"namespace": "quizzlepeople",
"id": "176694722487191"
}
},
{
"user": {
"name": "Michał Szydłowski",
"id": "100001699654797"
},
"score": 1,
"application": {
"name": "Friend Smash!",
"namespace": "friendsmashsample",
"id": "480369938658210"
}
},
{
"user": {
"name": "Michał Szydłowski",
"id": "100001699654797"
},
"score": 0,
"application": {
"name": "Wordox",
"namespace": "wordox-the-game",
"id": "227993680602156"
}
},
{
"user": {
"name": "Michał Szydłowski",
"id": "100001699654797"
},
"score": 0,
"application": {
"name": "SongPop",
"namespace": "songpop",
"id": "323595464361460"
}
}
]
}
How do I extract useful data from this?
I'm trying to take something as a JSONObject, using:
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet("https://graph.facebook.com/me?fields=score&access_token=" + token);
HttpResponse resp = client.execute(get);
Log.i("info1", resp.toString());
// Parse the response
HttpEntity responseEntity = resp.getEntity();
String response = EntityUtils.toString(responseEntity);
Log.i("info1", response);
JSONObject result = new JSONObject(response);
JSONArray arr = result.getJSONArray("data");
Log.i("info2", arr.toString());
just to see if I can take anything, say, the array named 'data'. Yet the logcat does not show me anything. It shows the first 2 logs, but not the 3rd. Any ideas?
That looks like JSONObject. You can loop thru it and do whatever you wish with the data.
Have a look at http://json.org/ for documentation for a specific language (I presume you need java so click on the java link).
I appended the data to a table to give you an idea ( jquery / javascript ):
fiddle:http://jsfiddle.net/H8LNB/4/

Categories