Get a nested value from a json api - android

I have this json code
{
"status": "success",
"message": null,
"data": {
"19": {
"id": "19",
"created": "2019-01-07 13:26:06",
"createdby": 158,
"touched": "2019-01-07 13:26:06",
"touchedby": 158,
"start": "2019-01-07",
"end": "2019-01-08",
"scoperole": 3,
"scopecorp": 1,
"body": "<p>test</p>",
"language": "en"
},
"20": {
"id": "20",
"created": "2019-01-07 13:26:20",
"createdby": 158,
"touched": "2019-01-07 13:26:20",
"touchedby": 158,
"start": "2019-01-07",
"end": "2019-01-08",
"scoperole": 3,
"scopecorp": 1,
"body": "<p>test1</p>",
"language": "en"
}
},
"error": 0,
"line": 1515,
"debug": null
}
And i want to take the values of "body" (test,test1).
How can i reach them?I left the code that i tried just to see it with //not working next to it.Any ideas please?Also the 19,20 are not the same so i'm not able to get them by just putting the name of a variable(ex JSONObject dataObj =new JSONObject ("data");
Here is my code
private void getJson() {
URL obj = null;
try {
obj = new URL("https://gekon.technologypark.cz/api/v1/notification/");
HttpsURLConnection conn = (HttpsURLConnection) obj.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("ApiSecret", LoginInfo.ApiSecret);
conn.connect();
BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
StringBuilder sb = new StringBuilder();
String output;
while ((output = br.readLine()) != null)
sb.append(output);
JSONObject jsonObj = new JSONObject(sb.toString());
Log.d("test", "response" + jsonObj);
JSONObject dataObj =new JSONObject("data");
JSONObject dataObj19 =dataObj.getJSONObject("22");
String body1 =dataObj19.getString("body");
Log.d("test", "TEST ID" + body1);
pushNotification(notifText);
} catch (Exception e) {
e.printStackTrace();
Log.d("test", "PUSH CATCH" + e);
}
}
Here are my logs
**2019-01-07 14:17:42.778 19712-19712/ibm.gekon.vasileiosvlachakis.gekon D/alekos:
response{"status":"success","message":null,"data":{"22":{"id":"22","created":"2019-01-07
14:11:55","createdby":158,"touched":"2019-01-07
14:11:55","touchedby":158,"start":"2019-01-07","end":"2019-01-08","scoperole":3,"scopecorp":1,"body":"test22</p>","language":"en"}},"error":0,"line":1515,"debug":null}
2019-01-07 14:17:42.785 19712-19712/ibm.gekon.vasileiosvlachakis.gekon
D/alekos: PUSH CATCHorg.json.JSONException: Value data of type
java.lang.String cannot be converted to JSONObject**

Here you can get the value of body key. but this is specific for 19 and 20 JSON object
JSONObject dataObj = new
JSONObject(sb.toString()).getJSONObject("data");
JSONObject dataObj19 =dataObj.getJSONObject("19");
String body1 =dataObj19.getString("body");
JSONObject dataObj20 =dataObj.getJSONObject("20");
String body2 =dataObj20.getString("body");
if Response has multiple JSON object inside data JSON object then you need a loop to retrieve it
JSONObject dataObj =new JSONObject("data");
for(int i=0;i<dataObj.length();i++){
JSONObject data =dataObj.getJSONObject(i);
String body =data .getString("body");
}

JSONObject json = new JSONObject(sb.toString());
String statistics = json.getString("data");
for(Iteraor key=json.keys();key.hasNext();) {
JSONObject keyValue = json.get(key.next());
//now keyValue contains the 19,20 and so on...
String body1 =keyValue.getString("body");
Log.d("test", "TEST ID" + body1);
}
Try this it might work.

best way is to make static key, but you can get all keys and then get value for each one
use
JSONObject dataObj =new JSONObject("data");
Iterator<String> keys=dataObj.keys();
while (keys.hasNext())
{
JSONObject currentObject =dataObj.getJSONObject(keys.next());
String currentBody =currentObject.getString("body");
Log.d("test", "TEST ID" + currentBody);
}`

In JSON response your key should always be static in order to get a particular response from the key.
Here check whether your data JSONObject contains that key or not for error handling.
try {
JSONObject jsonObj = new JSONObject(sb.toString());// assuming this as your main JSONObject
if(jsonObj.has("data")){
JSONObject dataObj =jsonObj.getJSONObject("data");
if(dataObj.has("19")){
JSONObject json19 = dataObj.getJSONObject("19");
// Now here check if the json19 contains the key that you want.
if(json19.has("body")){
String valueBody = json19.getString("body"); // this will give you the value of body
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}

Related

org.json.JSONArray cannot be converted to JSONObject Resttemplate

I got a little problem with getting my JSON Object.
try {
JSONObject jObject = new JSONObject( response.getBody());
JSONObject userObject = jObject.getJSONObject("data");
String nachricht = userObject.getString("nachricht");
String ausgeloest_von = userObject.getString("ausgeloest_von");
String erstellt_am = userObject.getString("erstellt_am");
I get the error at data of type org.json.JSONArray cannot be converted to JSONObject at the second line in my code snippet. I have the same code on a different API and its working.
{
"error": 200,
"message": "Daten gefunden",
"data": [
{
"id": "105",
"userid": "9981",
"userid_notfall": "9985",
"nachricht": "Notfall von Max",
"ausgeloest_von": "",
"status": "0",
"erstellt_am": "2017-11-28 18:10:48",
"aktualisiert_am": ""
}
]
}
This is what the response body looks like. I think the "[" brackets causing my problems. Any idea?
Thank you in advance!
Use this code:
JSONObject jObject = new JSONObject( response.getBody()); JSONArray userArray= jObject.getJSONArray("data");
for(int i =0;i < userArray.length();i++) {
JSONObject individualObject = userArray.getJSONObject(i);
String nachricht = userObject.getString("nachricht");
String ausgeloest_von = userObject.getString("ausgeloest_von"); String erstellt_am = userObject.getString("erstellt_am");
}

Json parsing error: Unterminated object at character 275 of

my code already get data(jsonstr) from website but can't make it to JSONObject and it make error Json parsing error: Unterminated object at character 2755
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JSONArray contacts = jsonObj.getJSONArray("Destinasi");
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String nim = c.getString("nama_destinasi");
String name = c.getString("alamat_destinasi");
String alamat= c.getString("deskripsi_destinasi");
and this link that i try to parse
https://ombajuom.000webhostapp.com/json_destinasi.php/Destinasi
please help me and sorry for my english
I see a misplaced ] and } in JSON String. The String it returns NOW is as follows
{
"Destinasi": [
{
"nomor_id": "1",
"nama_destinasi": "Ravi Tamada",
"alamat_destinasi": "Ciledug",
"deskripsi_destinasi": "WAhhh",
"rating_destinasi": "3"
]
}
}
But it should be as below to make it a valid JSON.
{
"Destinasi": [
{
"nomor_id": "1",
"nama_destinasi": "Ravi Tamada",
"alamat_destinasi": "Ciledug",
"deskripsi_destinasi": "WAhhh",
"rating_destinasi": "3"
}
]
}
Web service you shared is not a valid JSON format, to validate your response you can use jsonlint.com,
Thanks

Poorly formatted json parsing

I use code above to parse JSON in a try-catch.
JSONArray jsonRootObject = new JSONArray(text);
JSONArray jsonArray = jsonRootObject.optJSONArray(2);
name = jsonArray.toString();
Toast.makeText(MainActivity.this, name, Toast.LENGTH_LONG).show();
I use 2 as index in code below, because I would get values from candidates. I think, that is strange, because there isn't key-value pairs in array. I would like to get only the first key from this array (In this example subtest1.), its value isn't make sense.
{
"images": [
{
"time": 2.86091,
"transaction":
{
"status": "Complete",
"subject": "test2",
"confidence": 0.77,
"gallery_name": "gallerytest1",
},
"candidates": [
{
"subtest1": "0.802138030529022",
"enrollment_timestamp": "1416850761"
},
{
"elizabeth": "0.802138030529022",
"enrollment_timestamp": "1417207485"
},
{
"elizabeth": "0.777253568172455",
"enrollment_timestamp": "1416518415"
},
{
"elizabeth": "0.777253568172455",
"enrollment_timestamp": "1416431816"
}
]
} ]
}
Try this and see if it solves your problem
JSONArray CandidatesArr = new JSONArray(jsonRootObject.getString("candidates"));
JSONObject CandidatesOBJ = CandidatesArr.getJSONObject(0);
String name=CandidatesOBJ.getString("subtest1");
Edit
To check if your key subset1 exists or not try the following code:
String name=""
if(CandidatesOBJ.has("subtest1")){
name=CandidatesOBJ.getString("subtest1");
}
your parser should be like.FYI JSONArray does not have key-value pairs but JSONObject does.
JSONObject root = new JSONObject(text);
JSONArray jarray = root.optJSONArray("images);
if(jarray != null){
JSONObject jObject = jarray.optJSONObject(0);
if(jObject != null){
JSONArray candidates = jObject.optJSONArray("candidates");
JSONObject jObj = jarray.optJSONObject(0);
if(jObj != null){
String subTest = jObj.optString("subtest1");
}
}
}

How to parse json response android

How to parse this below json response. I am developing a booking app. The response i got from the server is
{"HotelInformationResponse": {
"#hotelId": "210985",
"customerSessionId": "0ABAA826-9AAF-5791-3692-A03326791310",
"HotelSummary": {
"#order": "0",
"hotelId": 210985,
"name": "Seattle Marriott Waterfront",
"address1": "2100 Alaskan Way",
"city": "Seattle",
"stateProvinceCode": "WA",
"postalCode": 98121,
"countryCode": "US",
"propertyCategory": 1,
"hotelRating": 4,
"tripAdvisorRating": 4,
"locationDescription": "Near Seattle Aquarium",
"highRate": 645,
"lowRate": 279,
"latitude": 47.61016,
"longitude": -122.34651
},
"HotelDetails": {
"numberOfRooms": 358,
"numberOfFloors": 8,
"checkInTime": "4:00 PM",
"checkOutTime": "12:00 PM",
"propertyInformation": "Pets not allowed Check-in time starts at 4 PM Check-out time is Noon ",
}
Any method is appreciated
I hope this code can help u
public static String Profile_response(String response){
try{
JSONArray jsonarray = new JSONArray("["+response+"]");
JSONObject jsonobject = jsonarray.getJSONObject(0);
parseForcitydetail1(jsonobject.getString("HotelInformationResponse"));
return response;
}catch (Exception e) {
return "\"" + "Access Denied" + "\"";
}
}
public static void parseForcitydetail1(String res){
try{
JSONArray jsonarray1 = new JSONArray(res);
for(int i=0;i<jsonarray1.length();i++){
JSONObject jsonobject = jsonarray1.getJSONObject(i);
Hotal_ID.add(jsonobject.getString("#hotelId"));
customer_ID.add(jsonobject.getString("customerSessionId"));
}
parseForcitydetail2(jsonobject.getString("HotelSummary"));
}catch (Exception e) {
System.out.println(e.toString());
}
}
public static void parseForcitydetail2(String res){
try{
JSONArray jsonarray1 = new JSONArray(res);
for(int i=0;i<jsonarray1.length();i++){
JSONObject jsonobject = jsonarray1.getJSONObject(i);
Order.add(jsonobject.getString("#order"));
hote_ID.add(jsonobject.getString("hotelId"));
Name.add(jsonobject.getString("name")); Address.add(jsonobject.getString("address1"));....
City.add(jsonobject.getString("city"));
StateProvinceCode.add(jsonobject.getString("stateProvinceCode")); PostalCode.add(jsonobject.getString("postalCode"));
CountryCode.add(jsonobject.getString("countryCode"));
PropertyCategory.add(jsonobject.getString("propertyCategory")); HotelRating.add(jsonobject.getString("hotelRating"));....
TripAdvisorRating.add(jsonobject.getString("tripAdvisorRating"));
LocationDescription.add(jsonobject.getString("locationDescription")); Latitude.add(jsonobject.getString("latitude"));
Longitude.add(jsonobject.getString("longitude"));
}
}catch (Exception e) {
System.out.println(e.toString());
}
}
This Same process with "HotelDetails" Parsing
Enjoy !
You may use JSONArray and JSONObject to parse it manually. but its boring and may require extra attention to keys while running in loops. The easiest and highly recommended way is to use Google Gson library to handle this automatically.
Using JSONOBject, JSONArray to contain data like JSONObject, JSONArray
Using methods like: getJSONObject(), getString(), getXXX(). . to get data which you want.
with XXX - data type like int, string
You will understand how to parse JSON in Android easily with the link which describes how to parse JSON clearly (Example):
http://www.technotalkative.com/android-json-parsing/
private JSONObject jObject;
jObject = new JSONObject(your response as string);
//this will give you json object for HotelInformationResponse
JSONObject menuObject = jObject.getJSONObject("HotelInformationResponse");
by this way you can get values
String hotelId = menuObject.getString("#hotelId");
String customerSessionId = menuObject.getString("customerSessionId");
//...rest are same do same thing for HotelDetails
for extra information Check this link

Parsing JSON response in Android

I am writing a httpget request for android that queries the foursquare api for nearby event. The JSON responce I receive back is
{"groups": [
{
"type": "Nearby",
"venues": [
{
"id": 2587838,
"name": "Marriott Druids Glen Hotel Newtownmountkennedy",
"primarycategory": {
"id": 79281,
"fullpathname": "Travel:Resort",
"nodename": "Resort",
"iconurl": "http://foursquare.com/img/categories/travel/resort.png"
},
"address": "Newtownmountkennedy",
"city": "Newtownmountkennedy",
"state": "",
"verified": false,
"geolat": 53.091717,
"geolong": -6.079162,
"stats": {
"herenow": "0"
},
"distance": 5596
},
There can be many of these venues. I can get it to print out the venues information using this code
InputStream instream = entity.getContent();
String result= convertStreamToString(instream);
Log.i("Hoosheer0",result);
// A Simple JSONObject Creation
JSONObject json=new JSONObject(result);
JSONArray venues = json.getJSONArray("groups");
//JSONArray docsArray = jObject.getJSONArray("docs");
for (int i = 0; i<venues.length();i++){
String name = venues.getJSONObject(i).optString("venues");
//String venueName = name.
Log.i("This is a name... pleasse", name);
}
instream.close();
How can I access the geolat & geolong values?
I believe placing this code inside your for-loop should do the trick:
JSONObject venueObject = venues.getJSONObject(i);
double geoLat = venueObject.getDouble("geolat");
double geoLong = venueObject.getDouble("geolong");
You can check here and pick a JSON library to use to get at those values.

Categories

Resources