Parsing JSON object from String - android
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.
Related
Json move to next item
I have a dynamic JSON string that looks like this: {"_id":"7","food_name":"Fiber Balance"},{"_id":"8","food_name":"Sport +"} I am able to get the first name, but not the second one. This is my code for getting the first (Fiber Balance): // Dynamic text TextView textViewDynamicText = (TextView)getActivity().findViewById(R.id.textViewDynamicText); String stringJSON = textViewDynamicText.getText().toString(); String stringFoodname = ""; try { JSONObject jsonObject = new JSONObject(stringJSON); Iterator<String> iter = jsonObject.keys(); while (iter.hasNext()) { String key = iter.next(); try { stringFoodname = jsonObject.getString("food_name"); Toast.makeText(getContext(), stringFoodname, Toast.LENGTH_LONG).show(); } catch (JSONException e) { // Something went wrong! } } } catch (org.json.JSONException e) { // Something went wrong! } How can I go to the next item in the json string?
If you have multiple data than you need to use Array,if you want to get all data from your json use below trick, String json = "{\"_id\":\"7\",\"food_name\":\"Fiber Balance\"},{\"_id\":\"8\",\"food_name\":\"Sport +\"}"; json = "[" + json + "]"; try { JSONArray array = new JSONArray(json); for (int i = 0; i < array.length(); i++) { JSONObject object = array.getJSONObject(i); String foodName = object.getString("food_name"); Log.e("FoodName:", foodName); } } catch (JSONException e) { e.printStackTrace(); Log.e("error", "json", e); }
Retrieving values from this JSON Object [duplicate]
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(); } }); } }
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(); }
jsonobject cannot be converted with multiple input possibilities
i made a asynctask routine to comunicate to all my webservices that looks as follows: protected String[] doInBackground(String... params) { String parameterString = params[0]; // effectieve http request met de parameters toegevoegd HttpClient client = new DefaultHttpClient(); HttpGet aanvraag = new HttpGet(server + parameterString); // foutanalyse van de http request try { HttpResponse antwoord = client.execute(aanvraag); StatusLine statuslijn = antwoord.getStatusLine(); int statuscode = statuslijn.getStatusCode(); if(statuscode != 200){ Log.i("statuscode verzending", "statuscode= "+ statuscode); return null; } InputStream jsonStream = antwoord.getEntity().getContent(); BufferedReader reader= new BufferedReader(new InputStreamReader(jsonStream)); StringBuilder builder = new StringBuilder(); String lijn; while((lijn = reader.readLine())!= null){ builder.append(lijn); } String jsonData = builder.toString(); // hier beginnen we met de json data te ontmantelen JSONArray json = new JSONArray(jsonData); String[] data = new String[35]; Log.i("jsonparser", "lengte geretourde data " + json.length()); for (int i = 0; i < json.length(); i++) { data[i] = json.getString(i).toString(); } return data; } catch (ClientProtocolException e){ e.printStackTrace(); } catch (IOException e){ e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } return null; } i use the routine everytime i connect to a webservice for my app, (i have about 15 of them) all these webservices are made (and used) by the programs my software supplier made now i would like to connect to them with my android app some of them are working others don't what i found out already in my search for this failure: some jsondata is returned in the form of: [ "42416", " ", " ", " " ] other webservices return data as: true but the ones i am strugling with the most are looking like: { "z00": "1 ", "z01": 10000, "z02": "18/06/2010", "z03": "A", "z04": "0000", "z05": 7735, "z06": "VANNUYSE BVBA", "z07": "DEEFA", "z08": 17170, "z09": "AFLEVEREN HELI IN GEBRUIK", "z10": "0000", "z11": "8770 ", "z12": "INTER ", "z13": "HELI ", "z14": "CPCD25 - C240 ", "z15": "48182 ", "z16": "", "z17": "N", "z18": "0030", "z19": 0, "z20": "X", "z21": " ", "z22": "J", "z23": "", "z24": 0, "z25": "22/06/2010", "z26": 16854, "z27": 0, "z28": "AFLEVEREN IN GEBRUIK", "z29": " " } how should i form my asynctask routine so she is able to work for all routines? because my routine works fine now for the first type of data but at 3th type i get an error (didn't tried yet for 2nd type) : JSONObject cannot be converted to JSONArray thanks already for al your help guys
If you don't know what(jsonObject or jsonArray) is coming, you may try something like this: try { JSONObject jsonObject = new JSONObject(jsonData); // handle jsonObject } catch (JSONException e) { // Try to parse it to a JSONAray. // Also you can check the exception message here to determine if jsonArray conversion is wanted try { JSONArray jsonArray = new JSONArray(jsonData); // handle jsonArray } catch (JSONException e) { // something which is not JsonObject or JsonArray! } } Or try this: Object jsonAsObject = new JSONTokener(jsonData).nextValue(); if (jsonAsObject instanceof JSONObject) { // it is JSONObject JSONObject jsonObject = (JSONObject) jsonAsObject; } else if (jsonAsObject instanceof JSONArray) { // it is JSONArray JSONArray jsonArray = (JSONArray) jsonAsObject; }