org.json.JSONObject creating JSONObject from string threw java.lang.RuntimeException - java

I've been trying to figure out why constructing a org.json.JSONObject from a string json would not work for very long.
Here is the json string (pretty)
{
"status": 200,
"message": "200 Request is valid",
"job": {
"Id": 1,
"Jobtitle": "Test Job",
"Description": "Asthma",
"Medicalcondition": "Asthma",
"Language": "English",
"Racereligion": "Chinese",
"Agegender": "50, Female",
"Hourlyprice": 42,
"Type": "caregiver",
"Date": "2019-05-12T00:00:00+08:00",
"Starttime": "2018-07-20T12:15:00+08:00",
"Endtime": "2018-07-20T18:15:00+08:00",
"Address": "1 Cluny Road",
"Latitude": 1.3152057,
"Longitude": 103.8162553,
"Creator": "xiurobert"
}
}
and minified (the one that I'm attempting to construct a JSONObject from)
String json = "{\"status\":200,\"message\":\"200 Request is valid\",\"job\":{\"Id\":1,\"Jobtitle\":\"Test Job\",\"Description\":\"Asthma\",\"Medicalcondition\":\"Asthma\",\"Language\":\"English\",\"Racereligion\":\"Chinese\",\"Agegender\":\"50, Female\",\"Hourlyprice\":42,\"Type\":\"caregiver\",\"Date\":\"2019-05-12T00:00:00+08:00\",\"Starttime\":\"2018-07-20T12:15:00+08:00\",\"Endtime\":\"2018-07-20T18:15:00+08:00\",\"Address\":\"1 Cluny Road\",\"Latitude\":1.3152057,\"Longitude\":103.8162553,\"Creator\":\"xiurobert\"}}";
Constructor
JSONObject jsonObject = new JSONObject(json)
However, this resulted in a java.lang.RuntimeException: Cannot evaluate org.json.JSONObject.toString()
I've even tried using gson to parse the string first and then output it back to the new JSONObject but it seems like it didn't work.
Any reasons why?

This is working perfectly
String json = "{\"status\":200,\"message\":\"200 Request is valid\",\"job\":{\"Id\":1,\"Jobtitle\":\"Test Job\",\"Description\":\"Asthma\",\"Medicalcondition\":\"Asthma\",\"Language\":\"English\",\"Racereligion\":\"Chinese\",\"Agegender\":\"50, Female\",\"Hourlyprice\":42,\"Type\":\"caregiver\",\"Date\":\"2019-05-12T00:00:00+08:00\",\"Starttime\":\"2018-07-20T12:15:00+08:00\",\"Endtime\":\"2018-07-20T18:15:00+08:00\",\"Address\":\"1 Cluny Road\",\"Latitude\":1.3152057,\"Longitude\":103.8162553,\"Creator\":\"xiurobert\"}}";
try
{
JSONObject jsonObject = new JSONObject(json);
Log.i("TAG", "a: "+jsonObject.toString());
} catch (JSONException e)
{
e.printStackTrace();
}
where are you getting error

In my case i have used org.json.JSONObject and org.json.JSONArray. Then i changed the imports to org.json.simple.JSONObject and org.json.simple.JSONArray and my code worked without any issues.

Related

should value must be quoted in JSON along with key

i have data
like this:
{
"status": "success",
"message": "Student Statement Report",
"data": {
"data": [{
"id": "45",
"transaction_no": "45",
"transaction_date": "2017-05-25",
"transaction_type": "invoice",
"transaction_amount": "1010.00",
"related_invoice_id": "45",
"balance_amount": "1010.00",
"related_user_id": "436",
"related_user_group": "student",
"description": "",
"created_by": "Principal",
"updated_by": "Principal",
"created_at": "2017-05-25 11:57:39",
"updated_at": "2017-05-25 11:57:39"
}],
"opening_balance": 0,
"dates": ["2017-05-22 00:00:00", "2017-05-28 23:59:59"]
}
}
JSONObject jsonObject = new JSONObject(response);
and i am geeting Json expection error from here
String openingBalance = jsonObject.getString("opening_balance");
"opening_balance": 0,
so, my biggest question is should that zero (value) should be quoted or not?
You have to parse it like this:
JSONObject jsonObject = new JSONObject(response);
JSONObject data = jsonObject.getJSONObject("data");//Get Data object
int openingBalance = data.getInt("opening_balance");//Get opening balance
If you read the number as an Integer then quotation is not necessary. But if your read it as a String then you have to put quotation.
To read as an Integer you can use getInt("json_key")
& for String getString("json_key").
JSONObject jsonObject = new JSONObject(response);
JSONObject data = jsonObject.getJSONObject("data");//Get Data object
int openingBalance = data.getInt("opening_balance");//Get opening balance

Facebook Messenger API: Send Structured Message(Java)

In using Facebook messenger to send structured messages using generic template based on official documentation here. 'm using Java to construct the JSON object. Whenever I send the JSON to Facebook I get a response "400- bad request"I. I tried comparing using an online tool, the java generated JSON to that provided in the documentation and apart from the variable names nothing else is different. Can't understand where I'm going wrong in constructing the JSON.
JSON Generated from Java Code..
{
"message": {
"attachment": {
"payload": {
"elements": [
{
"buttons": [
{
"title": "show website",
"type": "web_url",
"url": "https://google.com"
},
{
"payload": "sample payload",
"title": "Hi There",
"type": "postback"
}
],
"default_action": {
"fallback_url": "https://www.google.com/",
"messenger_extensions": true,
"type": "web_url",
"url": "https://www.google.com/",
"webview_height_ratio": "tall"
},
"image_url": "https://s3-ap-southeast-1.amazonaws.com/primary-4495.png",
"subtitle": "Sample Sub Title",
"title": "Sample Title"
}
],
"template_type": "generic"
},
"type": "template"
}
},
"recipient": {
"id": "988459377921053"
}
}
Corresponding Java Code..
JSONObject root1 = new JSONObject();
JSONObject c01 = new JSONObject();
JSONObject c11 = new JSONObject();
JSONObject attachment = new JSONObject();
JSONObject payload = new JSONObject();
JSONArray arrayButton= new JSONArray();
JSONArray arrayelements= new JSONArray();
JSONObject elementsObj = new JSONObject();
JSONObject defaultAction = new JSONObject();
JSONObject buttons1 = new JSONObject();
JSONObject buttons2 = new JSONObject();
root1.put("recipient", c01);
c01.put("id", userId);
root1.put("message", c11);
c11.put("attachment", attachment);
attachment.put("type", "template");
attachment.put("payload", payload);
payload.put("template_type", "generic");
payload.put("elements", arrayelements);
arrayelements.put(elementsObj);
elementsObj.put("title", "Sample Title");
elementsObj.put("image_url", "https://s3-ap-southeast-1.amazonaws.com/primary-4495.png");
elementsObj.put("subtitle", "Sample Sub Title");
elementsObj.put("default_action", defaultAction);
defaultAction.put("type", "web_url");
defaultAction.put("url", "https://www.google.com/");
defaultAction.put("messenger_extensions", true);
defaultAction.put("webview_height_ratio", "tall");
defaultAction.put("fallback_url", "https://www.google.com/");
buttons1.put("type", "web_url");
buttons1.put("url", "https://google.com");
buttons1.put("title", "show website");
arrayButton.put(buttons1);
buttons2.put("type", "postback");
buttons2.put("title", "Hi There");
buttons2.put("payload", "sample payload");
arrayButton.put(buttons2);
elementsObj.put("buttons", arrayButton);
As you can see when comparing the above json with the sample one provided in the official documentation, only the order of elements is different. Stuck on this problem for the past 2 days..Please help..
Found my mistake!!
Whenever we try to use messenger_extensions property we have to whitelist the domain name otherwise messenger platform will return 400 error. Since I didn't need messenger_extensions property, I removed the entire default action section and now messenger API is returning 200 code. In case you want to whitelist your domain you can follow the below link.
https://developers.facebook.com/docs/messenger-platform/thread-settings/domain-whitelisting

How to parse JSON with another json inside in java?

This is my JSON:
{
"results": [
{
"username": "bigglesworth",
"phone": "650-253-0000",
"createdAt": "2011-11-07T20:58:06.445Z",
"updatedAt": "2011-11-07T20:58:06.445Z",
"objectId": "3KmCvT7Zsb"
},
{
"username": "cooldude6",
"phone": "415-369-6201",
"createdAt": "2011-11-07T20:58:34.448Z",
"updatedAt": "2011-11-07T21:25:10.623Z",
"objectId": "g7y9tkhB7O"
}
]
}
How can I parse this json?
When I tried to parse this using jason I retrived this error message
"Exception in thread "main"
com.fasterxml.jackson.databind.JsonMappingException: Can not
deserialize instance of java.util.ArrayList out of START_OBJECT
token"
Without third party libraries, you can do something like
JSONObject jsonObject = new JSONObject(jsonAsString);
JSONArray results = jsonObject.getJSONArray("results");
for(int i=0; i<results.length(); i++) {
JSONObject result = results.getJSONObject(i);
String username = result.getString("username");
//...
}

Got JSONObject text must begin with '{' error

The error is last line throw JsonException
Client client = Client.create();
WebResource webResource = client.resource(baseUrl+"/jaspertemplate");
ClientResponse respons = webResource.accept("application/json")
.get(ClientResponse.class);
String output = respons.getEntity(String.class);
JSONObject obj1 = new JSONObject(output.trim());
My JSON:
[
{
"type": "folder",
"name": "PAM",
"path": "C:\\home\\sameer\\sample\\PAM",
"id": "PAM6",
"c‌​hildren": [
{
"type": "file",
"name": "Country_Report_View_PAM.jasper",
"path": "C:\\home\\‌​sameer\\sample\\PAM\\Country_Report_View_PAM.jasper",
"id": "Country_Report_View_PAM.j‌​asper7",
"children": []
}
]
}
]
You are expecting a JSONObject but it is returning a JSONArray.
Please check object's validity before use.
Following post can be used to check JSONObject or JSONArray:
Test if it is JSONObject or JSONArray

Cannot parse JSONArray using GSON

I have encountered a problem whilst developing my Android application. My problem is that I don't know how to parse JSON code from an URL using GSON. I searched Google and SO for about an hour or so, but nothing worked for me. Everything I found on the internet referred to custom JSON code, not code from an URL. Here is a small sample of the data I have.
{
"status": {
"error": "NO",
"code": 200,
"description": "none",
"message": "Request ok"
},
"geoLocation": {
"city_id": "147",
"city_long": "Saint-Laurent",
"region_short": "QC",
"region_long": "Quebec",
"country_long": "Canada",
"country_id": "43",
"region_id": "35"
},
"stations": [
{
"country": "Canada",
"price": "3.65",
"address": "3885, Boulevard Saint-Rose",
"diesel": "0",
"id": "33862",
"lat": "45.492367",
"lng": "-73.710915",
"station": "Shell",
"region": "Quebec",
"city": "Saint-Laurent",
"date": "3 hours agp",
"distance": "1.9km"
},
{
"country": "Canada",
"price": "3.67",
"address": "3885, Saint-Mary",
"diesel": "0",
"id": "33872",
"lat": "45.492907",
"lng": "-73.740715",
"station": "Shell",
"region": "Quebec",
"city": "Saint-Laurent",
"date": "3 hours agp",
"distance": "2.0km"
}
]
}
I am a beginner at JSON/GSON so I need a bit of help. Here is what I have:
try {
String sURL = "http://api.mygasfeed.com/stations/radius/(39.631439)/(-80.8005451)/(25)/reg/(price)/uc82wk25m0.json?callback=?";
URL url = new URL(sURL);
HttpURLConnection request = (HttpURLConnection) url.openConnection();
request.connect();
// Convert to a JSON object to print data
JsonParser jp = new JsonParser(); //from gson
JsonElement root = jp.parse(new InputStreamReader((InputStream) request.getContent())); //convert the input stream to a json element
JsonObject rootobj = root.getAsJsonObject(); //may be an array, may be an object.
longitude = rootobj.get("price").getAsString();
latitude = rootobj.get("address").getAsString();
} catch (Exception e) {
e.printStackTrace();
}
I tried a loop to parse the array but that failed miserably. Any help regarding this problem is highly appreciated.
------------------------------EDIT-----------------------------------------------
I am extremely sorry about the incorrrect JSON code. I have updated the code but still cannot figure out the solution.
You JSON is wrong:
"date": "3 hours agp",
"distance": "1.9km"
}
{
"country": "Canada",
To coorect it, you must add a ,
"date": "3 hours agp",
"distance": "1.9km"
},
{
"country": "Canada",
Try this, using the basic org.json.JSONObject and org.json.JSONArray it works fine for me...
// This string is the JSON you gave as imput
String json = "{ \"status\": { \"error\": \"NO\", \"code\": 200, \"description\": \"none\", \"message\": \"Request ok\" }, \"geoLocation\": { \"city_id\": \"147\", \"city_long\": \"Saint-Laurent\", \"region_short\": \"QC\", \"region_long\": \"Quebec\", \"country_long\": \"Canada\", \"country_id\": \"43\", \"region_id\": \"35\" }, \"stations\": [ {\"country\": \"Canada\",\"price\": \"3.65\",\"address\": \"3885, Boulevard Saint-Rose\",\"diesel\": \"0\",\"id\": \"33862\",\"lat\": \"45.492367\",\"lng\": \"-73.710915\",\"station\": \"Shell\",\"region\": \"Quebec\",\"city\": \"Saint-Laurent\",\"date\": \"3 hours agp\",\"distance\": \"1.9km\" }, {\"country\": \"Canada\",\"price\": \"3.67\",\"address\": \"3885, Saint-Mary\",\"diesel\": \"0\",\"id\": \"33872\",\"lat\": \"45.492907\",\"lng\": \"-73.740715\",\"station\": \"Shell\",\"region\": \"Quebec\",\"city\": \"Saint-Laurent\",\"date\": \"3 hours agp\",\"distance\": \"2.0km\" } ]}";
try{
JSONObject rootobj = new JSONObject(json);
JSONArray array = rootobj.getJSONArray("stations");
for( int i = 0; i < array.length(); i++){
JSONObject o = array.getJSONObject(i);
String price = o.getString("price");
String address = o.getString("address");
//...
}
}catch(JSONException jse){
// Manage Exception here
}
Try below code to fetch data from url and parse the response using Gson.
Note : Remove "?callback=?" from your url, that will remove "?(" from your response
try {
String sURL = "http://api.mygasfeed.com/stations/radius/(39.631439)/(-80.8005451)/(25)/reg/(price)/uc82wk25m0.json";
URL u = new URL(sURL);
HttpURLConnection request = (HttpURLConnection) u.openConnection();
request.setRequestMethod("GET");
request.connect();
int status = request.getResponseCode();
switch (status) {
case 200:
case 201:
BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream()));
JsonElement element = new Gson().fromJson (br, JsonElement.class);
JsonObject jsonObj = element.getAsJsonObject();
JsonArray jArray = jsonObj.get("stations").getAsJsonArray();
for (int i = 0, size = jArray.length(); i < size; i++) {
JSONObject jObj = jArray.getJSONObject(i);
System.out.println(" Price : " + jObj.get("price").toString());
System.out.println(" Address : " + jObj.get("address").toString());
}
}
} catch (MalformedURLException ex) {
// Manage Exception here
} catch (IOException ex) {
// Manage Exception here
}

Categories

Resources