Retrieving values from this JSON Object [duplicate] - android

This question already has answers here:
How to parse JSON in Java
(36 answers)
Closed 5 years ago.
I want parse this json and get the value of user :
name and base
"response": [
{
"user": {
"avatar": {
"base": "http://undermusic.ir/up/avatar/base_c966da5e756c4f79982cef797c317f369e97a7d78c4206426be8e09237433894file_avatar.jpg"
},
"name": "hadi",
}

Try something like this...
try {
JSONArray jsonArray = new JSONArray(response);
for (int i = 0;i<jsonArray.length();i++)
{
JSONObject jsonObject = jsonArray.getJSONObject(i);
// String name = jsonObject.getString("")
JSONObject jsonObject1_user = jsonObject.getJSONObject("user");
JSONObject jsonObject1_avater = jsonObject1_user.getJSONObject("avatar");
String base = jsonObject1_avater.getString("base");
String name = jsonObject1_user.getString("name");
Log.d("getbase_name","values "+base+" "+name);
}
} catch (JSONException e) {
e.printStackTrace();
}

Extracting data from JsonArray,Try something like this.
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JSONArray contacts = jsonObj.getJSONArray("response");
// Getting JSON User Object node
JSONObject userObj = contacts.getJSONObject("user");
//Getting name key from user object
String name = userObj.getString("name");
//Getting avatar node from user object
JSONObject avatarObj= userObj.getJSONObject("avatar");
//Getting base key from avatar object
String base= avatarObj.getString("base");
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG)
.show();
}
});
}
}

Related

Parsing JSON object from String

I am trying to parse the json object from the data at the end of the post using the following code but I seem to have problem converting the intial string to JSON and also extracting JSON object in the key values of "feed" and "entry".
protected void JSONparse(String result) {
//parse JSON data
try {
JSONObject reader = new JSONObject(result);
JSONObject head = reader.getJSONObject("feed").getJSONObject("entry").getJSONObject(result);
JSONArray jArray = new JSONArray(head);
for(int i=0; i < jArray.length(); i++) {
JSONObject jObject = jArray.getJSONObject(i);
String name = jObject.getString("name");
String location = jObject.getString("location");
String contact = jObject.getString("contact");
Toast toast = Toast.makeText(this, name+" "+location+" "+contact, Toast.LENGTH_SHORT);
toast.show();
} // End Loop
} catch (JSONException e) {
Log.e("JSONException", "Error: " + e.toString());
} // catch (JSONException e)
}
Data String:
{"version":"1.0","encoding":"UTF-8",
"feed":
{"xmlns":"http://www.w3.org/2005/Atom","xmlns$openSearch":"http://a9.com/-/spec/opensearchrss/1.0/","xmlns$gsx":"http://schemas.google.com/spreadsheets/2006/extended","id":{"$t":"https://spreadsheets.google.com/feeds/list/"key"/od6/public/values"},"updated":{"$t":"2018-09-17T01:06:22.497Z"},"category":[{"scheme":"http://schemas.google.com/spreadsheets/2006","term":"http://schemas.google.com/spreadsheets/2006#list"}],
"title":{"type":"text","$t":"Sheet1"},"link":[{"rel":"alternate","type":"application/atom+xml","href":"https://docs.google.com/spreadsheets/d/"key"/pubhtml"},{"rel":"http://schemas.google.com/g/2005#feed","type":"application/atom+xml","href":"https://spreadsheets.google.com/feeds/list/"key"/od6/public/values"},{"rel":"http://schemas.google.com/g/2005#post","type":"application/atom+xml","href":"https://spreadsheets.google.com/feeds/list/"key"/od6/public/values"},
{"rel":"self","type":"application/atom+xml",
"href":"https://spreadsheets.google.com/feeds/list/"key"/od6/public/values?alt\u003djson"}],
"author":[{"name":{"$t":"appsmedion"},"email":{"$t":"appsmedion#gmail.com"}}],"openSearch$totalResults":{"$t":"6"},"openSearch$startIndex":{"$t":"1"},
"entry":
[{"id":{"$t":"https://spreadsheets.google.com/feeds/list/"key"/od6/public/values/cokwr"},
"updated":{"$t":"2018-09-17T01:06:22.497Z"},
"category":[{"scheme":"http://schemas.google.com/spreadsheets/2006",
"term":"http://schemas.google.com/spreadsheets/2006#list"}],
"title":{"type":"text","$t":"Chris knight "},
"content":{"type":"text","$t":"location: Crows Nest NSW, type: dji, contact: na"},
"link":[{"rel":"self","type":"application/atom+xml",
"href":"https://spreadsheets.google.com/feeds/list/"key"/od6/public/values/cokwr"}],"gsx$name":{"$t":"Chris knight "},"gsx$location":{"$t":"Crows Nest NSW"},"gsx$type":{"$t":"dji"},
"gsx$contact":{"$t":"na"}},{"id":{"$t":"https://spreadsheets.google.com/feeds/list/"key"/od6/public/values/cpzh4"},"updated":{"$t":"2018-09-17T01:06:22.497Z"},"category":[{"scheme":"http://schemas.google.com/spreadsheets/2006","term":"http://schemas.google.com/spreadsheets/2006#list"}],"title":{"type":"text","$t":"Shayne Johnston"},"content":{"type":"text","$t":"location: Hay Nsw , type: dji, contact: 466863944"},"link":[{"rel":"self","type":"application/atom+xml","href":"https://spreadsheets.google.com/feeds/list/"key"/od6/public/values/cpzh4"}],"gsx$name":{"$t":"Shayne Johnston"},"gsx$location":{"$t":"Hay Nsw "},"gsx$type":{"$t":"dji"},"gsx$contact":{"$t":"466863944"}},{"id":{"$t":"https://spreadsheets.google.com/feeds/list/"key"/od6/public/values/cre1l"},"updated":{"$t":"2018-09-17T01:06:22.497Z"},"category":[{"scheme":"http://schemas.google.com/spreadsheets/2006","term":"http://schemas.google.com/spreadsheets/2006#list"}],"title":{"type":"text","$t":"Edward Morris"},"content":{"type":"text","$t":"location: Alkimos WA, type: dji, contact: edwardcmorris#yahoo.com.au"},"link":[{"rel":"self","type":"application/atom+xml","href":"https://spreadsheets.google.com/feeds/list/"key"/od6/public/values/cre1l"}],"gsx$name":{"$t":"Edward Morris"},"gsx$location":{"$t":"Alkimos WA"},"gsx$type":{"$t":"dji"},"gsx$contact":{"$t":"edwardcmorris#yahoo.com.au"}},{"id":{"$t":"https://spreadsheets.google.com/feeds/list/"key"/od6/public/values/chk2m"},"updated":{"$t":"2018-09-17T01:06:22.497Z"},"category":[{"scheme":"http://schemas.google.com/spreadsheets/2006","term":"http://schemas.google.com/spreadsheets/2006#list"}],"title":{"type":"text","$t":"Andy"},"content":{"type":"text","$t":"location: Wellington St Mulgrave VIC, type: dji, contact: 413556955"},"link":[{"rel":"self","type":"application/atom+xml","href":"https://spreadsheets.google.com/feeds/list/"key"/od6/public/values/chk2m"}],"gsx$name":{"$t":"Andy"},"gsx$location":{"$t":"Wellington St Mulgrave VIC"},"gsx$type":{"$t":"dji"},"gsx$contact":{"$t":"413556955"}},{"id":{"$t":"https://spreadsheets.google.com/feeds/list/"key"/od6/public/values/ciyn3"},"updated":{"$t":"2018-09-17T01:06:22.497Z"},"category":[{"scheme":"http://schemas.google.com/spreadsheets/2006","term":"http://schemas.google.com/spreadsheets/2006#list"}],"title":{"type":"text","$t":"Cody"},"content":{"type":"text","$t":"location: Alice Spring NT, type: parrot, contact: 412222222"},"link":[{"rel":"self","type":"application/atom+xml","href":"https://spreadsheets.google.com/feeds/list/"key"/od6/public/values/ciyn3"}],"gsx$name":{"$t":"Cody"},"gsx$location":{"$t":"Alice Spring NT"},"gsx$type":{"$t":"parrot"},"gsx$contact":{"$t":"412222222"}},{"id":{"$t":"https://spreadsheets.google.com/feeds/list/"key"/od6/public/values/ckd7g"},"updated":{"$t":"2018-09-17T01:06:22.497Z"},"category":[{"scheme":"http://schemas.google.com/spreadsheets/2006","term":"http://schemas.google.com/spreadsheets/2006#list"}],"title":{"type":"text","$t":"Anthony "},"content":{"type":"text","$t":"location: Bundaberg , type: dji, contact: anthonycarrick1978#yahoo.com.au"},"link":[{"rel":"self","type":"application/atom+xml","href":"https://spreadsheets.google.com/feeds/list/"key"/od6/public/values/ckd7g"}],"gsx$name":{"$t":"Anthony "},"gsx$location":{"$t":"Bundaberg "},"gsx$type":{"$t":"dji"},"gsx$contact":{"$t":"anthonycarrick1978#yahoo.com.au"}}]}}
Looks like JSON is incorrect.
Even if JSON would be correct - "entry" is an array, not an object. Try this code:
protected void JSONparse(String result) {
//parse JSON data
try {
JSONObject reader = new JSONObject(result);
JSONArray jArray = reader.getJSONObject("feed").getJSONArray("entry");
for(int i=0; i < jArray.length(); i++) {
JSONObject jObject = jArray.getJSONObject(i);
String name = jObject.getString("gsx$name");
String location = jObject.getString("gsx$location");
String contact = jObject.getString("gsx$contact");
Toast toast = Toast.makeText(this, name+" "+location+" "+contact, Toast.LENGTH_SHORT);
toast.show();
} // End Loop
} catch (JSONException e) {
Log.e("JSONException", "Error: " + e.toString());
} // catch (JSONException e)
}
Try to fix your json string first.
Easiest ways to do it is web pages like https://jsoneditoronline.org/ ...
Or simply create your_file_name.json file in Android studio and let lint to show you where error or errors is.

parsing JSON string for an array in Java

I am writing an Android application that pulls JSON data from an SQL db.
In my Async Task class, I receive a JSON string from an HTTP request and I assign it to a JSONObject. This string contains various data, including an array of coordinates which I need. After that, I do obj.getJSONArray("coordinates"); As soon as I do that, my application throws an exception:
org.json.JSONObject cannot be converted to JSONArray in android
I am following this post's approach to solve my issues but with no luck:
org.json.JSONObject cannot be converted to JSONArray in android
I feel like I need to iterate over my JSON string until I see that array. I will post the string data below.
protected Void doInBackground(Void... voids) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(address);
//Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONObject obj = new JSONObject(jsonStr);
JSONArray deviceJsonArray = obj.getJSONArray("coordinates"); //ERROR OCCURS HERE!
// looping through All Devices
for (int i = 0; i < deviceJsonArray.length(); i++) {
JSONObject json = deviceJsonArray.getJSONObject(i);
//String DeviceID = c.getString("id");
// longitude = json.getDouble("longitude");
// latitude = json.getDouble("latitude");
Device device = new Device();
device.setName(receivedDeviceName);
//Adding the information to the array.
coordinatesArray.add(device);
}
//Log.e(TAG, "arraylist: " + coordinatesArray);
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG)
.show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG)
.show();
}
});
}
return null;
}
JSON string value:
{"data":{"type":"gps","total_distance":18,"coordinates":[{"latitude":49.169209,"longitude":-122.990952,"time":"12:02:38 AM"},{"latitude":49.16922,"longitude":-122.990959,"time":"2:42:33 PM"},{"latitude":49.1693,"longitude":-122.988098,"time":"5:16:33 PM"},{"latitude":49.170979,"longitude":-122.968239,"time":"5:18:33 PM"},{"latitude":49.174992,"longitude":-122.962502,"time":"5:20:33 PM"},{"latitude":49.17688,"longitude":-122.95768,"time":"5:22:33 PM"},{"latitude":49.182232,"longitude":-122.960297,"time":"5:24:33 PM"},{"latitude":49.18581,"longitude":-122.950813,"time":"5:26:33 PM"},{"latitude":49.188869,"longitude":-122.945969,"time":"5:28:33 PM"},{"latitude":49.197689,"longitude":-122.948502,"time":"5:30:33 PM"},{"latitude":49.20216,"longitude":-122.947418,"time":"5:32:33 PM"},{"latitude":49.2071,"longitude":-122.949593,"time":"5:34:33 PM"},{"latitude":49.213051,"longitude":-122.938522,"time":"5:36:33 PM"},{"latitude":49.215462,"longitude":-122.93399,"time":"5:38:33 PM"},{"latitude":49.216381,"longitude":-122.932297,"time":"5:40:33 PM"},{"latitude":49.218769,"longitude":-122.92791,"time":"5:42:33 PM"},{"latitude":49.221062,"longitude":-122.923653,"time":"5:44:33 PM"},{"latitude":49.227119,"longitude":-122.912392,"time":"5:46:33 PM"},{"latitude":49.234489,"longitude":-122.89872,"time":"5:48:33 PM"},{"latitude":49.235699,"longitude":-122.894608,"time":"5:50:33 PM"},{"latitude":49.241928,"longitude":-122.89257,"time":"5:52:33 PM"},{"latitude":49.241871,"longitude":-122.89016,"time":"6:02:33 PM"}]}}
Could someone see what I am doing wrong or recommend a fix please?
Try this instead:
JSONObject obj = new JSONObject(jsonStr);
JSONObject objData = obj.getJSONObject("data");
JSONArray deviceJsonArray = objData.getJSONArray("coordinates");
The "coordinates" JSONArray is one element deeper in your JSON structure

Get value json not in a array

When I'm JSONObject jsonObj = new JSONObject(jsonStr);
I enter in catch because my json is not a array.
How can I get this format ?
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String url = "http://10.0.2.2:8080/PFA/crimes";
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 data = jsonObj.getJSONArray("crime");
// looping through All Contacts
for (int i = 0; i < data.length(); i++) {
JSONObject c = data.getJSONObject(i);
String day_week = c.getString("day_week");
String naturecode = c.getString("naturecode");
// tmp hash map for single contact
HashMap<String, String> contact = new HashMap<>();
// adding each child node to HashMap key => value
contact.put("day_week", day_week);
contact.put("naturecode", naturecode);
// adding contact to contact list
List.add(contact);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG).show();
}
});
}
return null;
}
JSON:
{
"crime": {
"compnos": "zerezrerzerezzr",
"day_week": "rtkeertoeirtj ,ertkierj",
"domestic": "false",
"fromdate": "ekrjtner",
"id": "1",
"location": "etritkjrtoijty",
"main_crimecode": "oijereriotjeroi",
"month": "455",
"naturecode": "zetzeeztet",
"reportingarea": "58",
"reptdistrict": "zorigjrgoijtoi",
"shift": "rektenrloj",
"shooting": "true",
"streetname": "kjrtnerkj",
"ucrpart": "irtjeroitejroirj",
"weapontype": "kejfnergkrtnh",
"x": "11",
"xstreetname": "zekjrnetk",
"y": "11",
"year": "45"
}
}
JsonObject crime = jsonObj.getJsonObject("crime");
JsonObject compnos = crime.getJsonObject("compnos");
.
..
...
There is no jsonArray in your json value. Give up to get jsonArray.
Try this:
JSONObject jsonObj = new JSONObject(jsonStr);
JSONObject jsonMetaObject = jsonMasterObject.getJSONObject("crime");
instead of
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JSONArray data = jsonObj.getJSONArray("crime");
Because you get jsonObject in key of crime not JsonArray.

Parsing a JSON file without arrays

I am trying to parse this: https://s3.amazonaws.com/dolartoday/data.json for an Android app that shows the dollar to bolivar unofficial exchange rate.
I am using this tutorial: http://www.androidhive.info/2012/01/android-json-parsing-tutorial/, which I have used successfully before, however previous APIs I have used consisted of a JSON array with child objects. This one, however, has 12 JSON objects with strings. No square brackets to be seen.
The part (I think) I'm having trouble with is:
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JSONArray contacts = jsonObj.getJSONArray("contacts");
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String id = c.getString("id");
String name = c.getString("name");
String email = c.getString("email");
String address = c.getString("address");
String gender = c.getString("gender");
// Phone node is JSON Object
JSONObject phone = c.getJSONObject("phone");
String mobile = phone.getString("mobile");
String home = phone.getString("home");
String office = phone.getString("office");
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG)
.show();
}
});
}
}
I'm no expert, since I'm trying to learn programming on my own and I'm still very new. However, I have made some changes including getting rid of the ListView, and adapting the code to the new JSON.
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Object node
JSONObject c = jsonObj.getJSONObject("USD");
JSONObject d = jsonObj.getJSONObject("EUR");
String usdtrans = c.getString("dolartoday");
String usdreal = c.getString("efectivo_real");
String usddicom = c.getString("sicad2");
String eurtrans = d.getString("dolartoday");
String eurreal = d.getString("efectivo_real");
String eurdicom = d.getString("sicad2");
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG)
.show();
}
});
}
}
The code does not compile, and Android Studio detects an "unhandled exception: org.json.JSONException". What can I do to change this?
Any help would be appreciated. The rest of my code has other issues as well, but I think I can sort those out once I can get this one done.
While using org.json library classes, If the JSON response consists of square bracket "[" then we need to get that element as JSONArray else get the element as JSONObject.
try {
JSONObject jsonObject = new JSONObject(jsonString);
JSONObject antibloqueo = jsonObject.getJSONObject("_antibloqueo");
JSONObject labels = jsonObject.getJSONObject("_labels");
JSONObject timestamp = jsonObject.getJSONObject("_timestamp");
JSONObject USD = jsonObject.getJSONObject("USD");
JSONObject EUR = jsonObject.getJSONObject("EUR");
JSONObject COL = jsonObject.getJSONObject("COL");
JSONObject GOLD = jsonObject.getJSONObject("GOLD");
JSONObject USDVEF = jsonObject.getJSONObject("USDVEF");
JSONObject USDCOL = jsonObject.getJSONObject("USDCOL");
JSONObject EURUSD = jsonObject.getJSONObject("EURUSD");
JSONObject BCV = jsonObject.getJSONObject("BCV");
JSONObject MISC = jsonObject.getJSONObject("MISC");
//To get Values From antibloqueo
String mobile = antibloqueo.getString("mobile");
String video = antibloqueo.getString("video");
//To get Values From labels
String a = labels.getString("DOLARTODAY");
String a1 = labels.getString("a1");
} catch (JSONException e) {
Log.e("TAG", "Json parsing error: " + e.getMessage());
}
Note:
While working with smaller projects you can use org.json library as the JSON Convertor. For the bigger projects you have to use other libraries like Gson /Jackson
https://www.mkyong.com/java/how-do-convert-java-object-to-from-json-format-gson-api/

how can decode json data form api in android?

I am geting JSON data getting from web service. Below is my code.
How can I decode the json data?
{
"response": [
{
"last_name": "Test",
"id": 279711390,
"first_name": "Vishnu",
"sex": 2,
"photo_50": "https://vk.com/images/camera_50.gif"
}
]
}
How can I parse it? Thanks.
You can keep a POJO class. With the data which you are about to get from server. And parse them and save in that object.
Example:
JSONObject json= new JSONObject(responseString); //your response
try {
JSONArray responseArray = jsonObj.getJSONArray("response");
for (int i = 0; i < responseArray.length(); i++) {
// get value with the NODE key
JSONObject obj = responseArray.getJSONObject(i);
String lastName = obj.getString("last_name");
String firstName = obj.getString("first_name");
//same for all other fields in responseArray
MyResponse myResp = new MyResponse();
myResp.setFirstName(firstName);
myResp.setLastName(lastName);
//set all other Strings
//lastly add this object to ArrayList<MyResponse> So you can access all data after saving
}
}
catch (JSONException e) {
e.printStackTrace();
}
POJO Class:
public class MyResponse{
public String firstName="";
public String lastName="";
//all other fields and getter setters
}
Hope this helps.
You can parse JSON using this code:
str="<The Json>"
try {
JSONObject jObject=new JSONObject(str);
JSONArray menuObject = new JSONArray(jObject.getString("response"));
String lastName;
for (int i = 0; i<menuObject.length(); i++) {
lastName=menuObject.getJSONObject(i).getString("last_name").toString();
...
}
catch (JSONException e) {
e.printStackTrace();
}
Use this code :-
String string = "Your Json"
try {
JSONObject jsonObject=new JSONObject(str);
JSONArray menuObject = new JSONArray(jObject.getJsonArray("response"));
//no need of for loop because you have only one object in jsonArray.
JSONObject oject = menuObject.getJSONObject(0);
String lastName = object.getString("last_name");
String firstName = object.getString("first_name");
Log.d("User Name", firstName + " " + lastName);
catch (JSONException e) {
e.printStackTrace();
}

Categories

Resources