Cannot show null object in jsonobject - java

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

Related

Dynamic response of Retrofit

My answer Json depends on whether it succeeds or not.
Unsuccessful example:
{
"success": false,
"errors": {
"email": "Could not find email address"
}
}
Successful example:
{
"success": true,
"user": {
"id": 6,
"fname": "XXXXXX",
"lname": "XXXXXX",
"email": "Username#mail.ca",
"roles": [
"Player"
"Coach"
"manager",
"Admin"
]
"date_registered": "2018-03-16T17: 49: 05.000Z"
}
"Token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzaWQiOiJiNjU1MDVkOGJiYzZhMTg1Y2E5MjU5NDlmNTU0OTc0MTgzM2Y2N2NiNjFjYThkMzNkMTUxY2U2MDhjMTBmNTllIiwiaWF0IjoxNTI3MjY3MzEwLCJleHAiOjE1Mjc4NzIxMTB9.p5pTlNjTsr-8N_8B3M5fW3T6PTTrcFo8D77N0WWgA3c"
}
Now, I want to have a POJO for both at the same time with retrofit.
Thank you
Edit : I just solved the problem by changing the form of JSON to :
{
"success": true,
"data": {
"user": {
"id": 6,
"fname": "XXXXXXX",
"lname": "XXXXXXXX",
"email": "Username#mail.ca",
"roles": [
"player",
"coach",
"manager",
"admin"
],
"activation_state": 0,
"date_registered": "2018-03-16T17:49:05.000Z"
},
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzaWQiOiI0MTFlZmI5Y2ExYzY1ZWFlYzQ4Yzg1ZjJkYTQwOThmODBjOTk1NWNjNjcyOTNlODI5NmI4N2RjZWY5OTMzYzljIiwiaWF0IjoxNTI4NDI0MDA1LCJleHAiOjE1Mjg0MjQ2MDl9.lTsQ867Lk78RV2ruaQFyxUNfm58bHpfzEsZnvKJQMXQ"
},
"errors": {}
}
Thank you for help
You could simply return a String Retrofit, and then parse it manually.
If not, then you have to create a POJO object that contains all variables from both objects.
And then at runtime you check if "success" is true/false, and then try to access the underlying varaibles.
Copy your json response and past http://pojo.sodhanalibrary.com/
Then submit
You will get multiple pojo class with respect to your response ,

How to get a child attribute from JSONObject Java

I have a problem in my code where I need to print a child attribute from a JSONObject. Actually, I want to have the attribute values in a JSONArray because of some purposes.
<--So far I did-->
String preStringSingle = responseSingle.body().string(); // has the JSONObject
JSONObject resultsJObject = new JSONObject(preStringSingle);
JSONArray resultsJArray1 = resultsJObject.optJSONArray("data");
System.out.println(resultsJArray1);
<--JSONObject-->
"status": true,
"locale": "en-US",
"error_code": null,
"message": "OK",
"data": [
{
"service_list_access_mode": 0,
"service_list_domain": "http://www.hotsalesmarket.com",
"service_list_auth_method": 0,
"service_list_auth_user": null,
"service_list_auth_password": null,
"http_method": "GET",
"map_service_lists": [
{
"path": "sdfm.assets/assets/cameras/5799.jpg",
"service_item_id": 5799
},
{
"path": "dsf.assets/assets/cameras/5798.jpg",
"service_item_id": 5798
},
{
"path": "sdfsdf.assets/assets/cameras/6701.jpg",
"service_item_id": 6701
}
]
}
],
"timestamp": "2017-06-20T03:46:38Z"
}
I wanted to get all the details in the child attribute "map_service_lists".
<--Desired output-->
{
"path": "sdfsdf.assets/assets/cameras/5799.jpg",
"service_item_id": 5799
},
{
"path": "/sdfsdfs.assets/assets/cameras/5798.jpg",
"service_item_id": 5798
},
{
"path": "/sdfsdf.assets/assets/cameras/6701.jpg",
"service_item_id": 6701
}
You just have to continue like you did, but additional level down the hierarchy:
JSONArray data = resultsJObject.optJSONArray("data");
JSONObject firstData = data.optJSONObject(0);
JSONArray services = firstData.optJSONArray("map_service_lists");
System.out.println(services);
(Remove the array brackets from the result if you don't want them).
String preStringSingle = responseSingle.body().string();
JSONObject resultsJObject = new JSONObject(preStringSingle);
JSONArray resultsJArray1 = resultsJObject.optJSONArray("data");
JSONObject j = new JSONObject(resultsJArray1.get(0).toString());
JSONArray resultsJArray2 = j.optJSONArray("map_service_lists");
System.out.println(resultsJArray2);

Retrieve value Json field

I know that we have a lot of document on that but in my case I can't apply it.. I have a JSON file like that :
{
"Status": {
"Code": 0,
"Message": "Search OK"
},
"Applications": {
"Application": [{
"Id": 123,
"Name": "Bob"
},
...
]
}
}
I want to retrieve the value of the field "Name".
My code :
String jsonData = readFile("test.json");
JSONObject jobj = new JSONObject(jsonData);
JSONObject jobj2 = (JSONObject) jobj.get("Applications");
JSONArray jarr = new JSONArray(jobj2.getJSONArray("Application").toString());
After that I don't know what to do.. How can I resolve my problem?
Thanks a lot.
For this json:
{
"Status": {
"Code": 0,
"Message": "Search OK"
},
"Applications": {
"Application": [{
"Id": 123,
"Name": "Bob"
}]
}
}
Your code can looks like:
jsonObject
.getJSONObject("Applications")
.getJSONArray("Application")
.getJSONObject(0)
.getString("Name")

parsing complex json object

Hi I am trying to parse json object below. But the problem is, inside the profile attribute, there is an attribute called fields which is sometimes a json object and sometime an json-array, so it is creating a problem when i am trying to use Gson to parse it. I followed this link but it didn't help How to dynamically handle json response array/object using Gson , so help is needed from someone who encountered this before, thanks!.
{
"users": {
"profile": [
{
"fields": {
"key": "fname",
"value": "Michael"
}
},
{
"fields": [
{
"key": "lname",
"value": "Bob"
},
{
"key": "age",
"value": "25"
}
]
}
]
}
}

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