How to get particular values from JSON response by using Android code? - android

I need to get Particular Object values ( A, B, C, D) and related key values (#"name" ). After getting (A, B, C, D ) object values I need to list out into list view Android. Here below I have posted my sample code and response. Please help me.
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
contacts = jsonObj.getJSONArray("response");
Log.d("Response: ", "> " + contacts);
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
My JSON Response :
{"response" : [ {
"A" : [ {
"name" : "tango"
},
{
"name" : "ping"
}
],
"B" : [ {
"name" : "tango"
},
{
"name" : "ping"
}
]
} ]}

Use JSONObject keys() to get the key and then iterate each key to get to the dynamic value.
You can get dynamic keys like this
JSONObject responseDataObj = new JSONObject(responseData);
JSONArray responseArray = responseDataObj.getJSONArray("response");
for (int i = 0; i < responseArray.length(); i++) {
nodes = new ArrayList<ArrayList<String>>();//nodes ArrayList<ArrayList<String>> declared globally
nodeSize = new ArrayList<Integer>();//nodeSize ArrayList<Integer> declared globally
JSONObject obj = responseArray.getJSONObject(i);
Iterator keys = obj.keys();
while(keys.hasNext()) {
// loop to get the dynamic key
String currentDynamicKey = (String)keys.next();
//store key in an arraylist which is A,B,...
// get the value of the dynamic key
JSONArray currentDynamicValue = obj.getJSONArray(currentDynamicKey);
int jsonrraySize = currentDynamicValue.length();
int sizeInArrayList = jsonrraySize + 1;
nodeSize.add(sizeInArrayList);
if(jsonrraySize > 0) {
for (int ii = 0; ii < jsonrraySize; ii++) {
nameList = new ArrayList<String>();//nameList ArrayList<String> declared globally
if(ii == 0) {
JSONObject nameObj = currentDynamicValue.getJSONObject(ii);
String name = nameObj.getString("name");
System.out.print("Name = " + name);
//store name in an arraylist
nameList.add(name);
}
}
}
nodes.add(nameList);
}
}

You can use following method to parse your response and handle output as per requirement.
private void parseJson(String res) {
try {
JSONObject mainObject = new JSONObject(res);
JSONArray response = mainObject.getJSONArray("response");
for (int i = 0; i < response.length(); i++) {
JSONObject obj = response.getJSONObject(i);
JSONArray A = obj.getJSONArray("A");
for (int j = 0; j < A.length(); j++) {
JSONObject objA = A.getJSONObject(j);
String name = objA.getString("name");
// use or store name here
}
JSONArray B = obj.getJSONArray("B");
for (int k = 0; k < B.length(); k++) {
JSONObject objB = B.getJSONObject(k);
String name = objB.getString("name");
// use or store name here
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

This may work for you :
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
JSONArray contacts;
contacts = jsonObj.getJSONArray("response");
Log.d("Response: ", "> " + contacts);
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
JSONArray jsonArrayA=new JSONArray();
jsonArrayA=c.getJSONArray("A");
for(int j=0;j<jsonArrayA.length();j++){
String name=jsonArrayA.getJSONObject(j).getString("name");
Log.e("Name","name of jsonarray A "+i+" "+name);
}
JSONArray jsonArrayB=c.getJSONArray("B");
for(int k=0;k<jsonArrayB.length();k++){
String name=jsonArrayB.getJSONObject(k).getString("name");
Log.e("Name","name of jsonarray B "+i+" "+name);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}

Related

read Json data in android studio

I am building an app in android studio that uses JSON to acess to my postgresql where is my data and I am receiving the data this way:
[
{"id":"1","title":"12 May to 30 Jun"},
{"id":"2","title":"3 Jun to 20 Jun"}
]
I tried to find every where how to use JSONObject or JSONArray for "unlock" the data for pass it to other variables
After sometime trying and trying I found a way to
String finalJson = buffer.toString();
try {
JSONArray parentArray = new JSONArray(finalJson);
int count = 0;
int[] id = new int[parentArray.length()];
String[] title = new String[parentArray.length()];
StringBuffer finalBufferedData = new StringBuffer();
while (count < parentArray.length())
{
JSONObject finalObject = parentArray.getJSONObject(count);
id[count] = finalObject.getInt("id");
title[count] = finalObject.getString("title");
finalBufferedData.append(id[count] + " - " + title[count] + "\n");
count++;
}
return finalBufferedData.toString();
} catch (JSONException e) {
e.printStackTrace();
}
this way I was able to get the 2 rows from postgresql and show it (later will add it the app sqlite so it doesn't require always to check in my postgresql)
Here is the working code:
public void parseJson() {
// Response from API call
String response = "[{\"id\":\"1\",\"title\":\"12 May to 30 Jun\"},\n" +
"{\"id\":\"2\",\"title\":\"3 Jun to 20 Jun\"}]";
try {
JSONArray jsonArray = new JSONArray(response);
// Get all jsonObject from jsonArray
for (int i = 0; i < jsonArray.length(); i++)
{
JSONObject jsonObject = jsonArray.getJSONObject(i);
String id = null, title = null;
// Id
if (jsonObject.has("id") && !jsonObject.isNull("id")) {
id = jsonObject.getString("id");
}
// Title
if (jsonObject.has("title") && !jsonObject.isNull("title")) {
title = jsonObject.getString("title");
}
Log.d("SUCCESS", "JSON Object: " + "\nId: " + id
+ "\nTitle: " + title);
}
} catch (JSONException e) {
Log.e("FAILED", "Json parsing error: " + e.getMessage());
}
}
OUTPUT:
D/SUCCESS: JSON Object:
Id: 1
Title: 12 May to 30 Jun
D/SUCCESS: JSON Object:
Id: 2
Title: 3 Jun to 20 Jun
protected void onPostExecute(String result)
{
//result parameter should be final so that it can be used in cross thread operation
super.onPostExecute(result);
if (result != null) {
try {
JSONArray jsonArray = new JSONArray(result);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
String Brand = object.getString("UserName");
HashMap<String, String> itemList = new HashMap<String, String>();
itemList.put("UserName", Brand);
BrandList.add(itemList);
}
**adapter = new SimpleAdapter(Main2Activity.this, BrandList, R.layout.list, new String[]{"UserName"}, new int[]{R.id.txtTitel});
((AdapterView<ListAdapter>) listView).setAdapter(adapter);
} catch (Exception ex) {
ex.printStackTrace();
}
} else {
Toast.makeText(Main2Activity.this, "Could not get any data.", Toast.LENGTH_LONG).show();
}
}

How to parse Complex JSON data of spreadsheet in android?

I am new to android, As I am trying to parse the Google's spreadsheet data and it is somewhat complex to me, I have to fetch $t of gsx$tag and $t of gsx$datetime,
This is the link from which we can get the JSON data
https://spreadsheets.google.com/feeds/list/1_AR0zX6Jv0NI_R1HBULbPEIUuJ2mqVbLoHVvLqOwu1I/1/public/values?alt=json
Data look like this
{
"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":{ },
"updated":{ },
"category":[ ],
"title":{ },
"link":[ ],
"author":[ ],
"openSearch$totalResults":{ },
"openSearch$startIndex":{ },
"entry":[
{
"id":{ },
"updated":{ },
"category":[ ],
"title":{ },
"content":{ },
"link":[ ],
"gsx$id":{
"$t":"1"
},
"gsx$datetime":{
"$t":"3/28/2017"
},
"gsx$tag":{
"$t":"21"
}
},
{ Data here },
{ Data here }
]
}
}
and below is the code I am trying
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);
JSONObject mainObj = new JSONObject(jsonStr);
Log.e(TAG,"JSon Data"+mainObj);
if (mainObj != null) {
Log.e(TAG,"JSon before feed"+mainObj.toString());
JSONArray a = mainObj.getJSONArray("feed");
Log.e(TAG,"JSon after feed"+a.toString());
JSONObject entru= new JSONObject((Map) a);
JSONArray list = entru.getJSONArray("entry");
// JSONArray entryarray = list.getJSONArray("entry");
if (list != null) {
for (int i = 0; i < list.length(); i++) {
JSONObject elem = list.getJSONObject(i);
if (elem != null) {
JSONArray prods = elem.getJSONArray("gsx$tag");
if (prods != null) {
for (int j = 0; j < prods.length(); j++) {
JSONObject innerElem = prods.getJSONObject(j);
if (innerElem != null) {
String sku = innerElem.getString("$t");
Log.e(TAG, "$t" + sku);
HashMap<String, String> contact = new HashMap<>();
contact.put("$t Datetime", sku);
// adding contact to contact list
contactList.add(contact);
}
}
}
}
}
}
}
Help Me in this regards, Thank you in advance
JSONArray a = mainObj.getJSONArray("feed");
Log.e(TAG,"JSon after feed"+a.toString());
JSONObject entru= new JSONObject((Map) a);
replace this 3 lines with the below one
JSONObject entru= mainObj.getJSONObject("feed");
also replace this line
JSONArray prods = elem.getJSONArray("gsx$tag");
with this one
JSONObject prods = elem.getJSONObject("gsx$tag");
I think this is the correct code.
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);
JSONObject mainObj = new JSONObject(jsonStr);
Log.e(TAG,"JSon Data"+mainObj);
if (mainObj != null) {
Log.e(TAG,"JSon before feed"+mainObj.toString());
JSONObject entru= mainObj.getJSONObject("feed");
JSONArray list = entru.getJSONArray("entry");
//JSONArray entryarray = list.getJSONArray("entry");
if (list != null) {
for (int i = 0; i < list.length(); i++) {
JSONObject elem = list.getJSONObject(i);
if (elem != null) {
JSONObject prods = elem.getJSONObject("gsx$tag");
if (prods != null) {
for (int j = 0; j < prods.length(); j++) {
String sku = prods.getString("$t");
Log.e(TAG, "$t" + sku);
HashMap<String, String> contact = new HashMap<>();
contact.put("$t Datetime", sku);
// adding contact to contact list
contactList.add(contact);
}
}
}
}
}
}
Please try this. If this doesn't work please feel free to ask. will help you
You can try using Gson or Jackson

Access Nested JSON Android

I want to know how do I access the values of this JSON in Android:
{
"dados": [{
"Id": 3,
"IdChamado": 3,
"Chamado": "value",
"Solicitante": "value",
"Acao": "",
"ItemDeCatalogo": "Mobile | Instalação",
"InicioPrevisto": "06/01/2017 08:11:00",
"TerminoPrevisto": "06/01/2017 08:22:00"
}, {
"Id": 4,
"IdChamado": 4,
"Chamado": "value",
"Solicitante": "value",
"Acao": "",
"ItemDeCatalogo": "value",
"InicioPrevisto": "06/01/2017 08:11:34",
"TerminoPrevisto": "06/01/2017 08:11:34"
}],
"success": true,
"erroAplicacao": false
}
I need to access the values "IdChamado", "chamado", "Solicitante", for example. I've seen nested arrays answers but with jsonObjects having an actual name, like this .
PS: I'm sorry I forgot to post my codes:
//Method called when the doInBack is complete
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
JSONObject jsonObject = new JSONObject(result);
JSONArray jArray = jsonObject.getJSONArray("dados");
Log.i("***2nd JSON ITSELF***", result);
for (int i=0; i<jArray.length(); i++) {
JSONObject jsonPart = jArray.getJSONObject(i);
int id = jsonPart.getInt("id");
Log.i("***id***", String.valueOf(id));
String chamado = jsonPart.getString("Chamado");
Log.i("***Chamado***", chamado);
String solicitante = jsonPart.getString("solicitante");
Log.i("***Solicitante***", solicitante);
String itemDeCatalogo = jsonPart.getString("itemDeCatalogo");
Log.i("***Item de Catalogo***", itemDeCatalogo);
}
}catch(JSONException e) {
e.printStackTrace();
}// END CATCH
}// END POST EXECUTE
[SOLVED]: Thank you so much people, you are the reason I like to code (Not be afraid of asking stupid questions). It all worked well with the codes you sent as answer. I thought it would be more complicated. xD
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
JSONObject jsonobject = new JSONObject(result);
JSONArray jsonarray = jsonobject.getJSONArray("dados");
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject jobject = jsonarray.getJSONObject(i);
String idChamado = jobject.getString("IdChamado");
String solicitante = jobject.getString("Solicitante");
Log.i("**id**", idChamado);
Log.i("**solicitante**", solicitante);
}
}catch(JSONException e) {
e.printStackTrace();
}// END CATCH
}// END POST EXECUTE
JSONObject jsonobject = new JSONObject("your JSON String here");
JSONArray jsonarray = jsonobject.getJSONArray("dados");
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject jsonobject = jsonarray.getJSONObject(i);
String IdChamado = jsonobject.getString("IdChamado");
String Solicitante = jsonobject.getString("Solicitante");
}
please try this
try this:
try{
JSONObject json = new JSONObject(jsonString);
JSONArray jsonArray = json.getJSONArray("dados");
for(int i=0;i<jsonArray.length();i++){
JSONObject object = jsonArray.getJSONObject(i);
String IdChamado = object.getString("IdChamado");
String Chamado = object.getString("Chamado");
//rest of the strings..
}
}
catch (JSONException e){
e.printStackTrace();
}
Try this
for (int i=0; i<jArray.length(); i++) {
JSONObject jsonobject = jArray.getJSONObject(i);
int IdChamado = jsonobject.getInt("IdChamado"); //idchamado here
String chamado = jsonobject.getString("Chamado");
String solicitante = jsonobject.getString("Solicitante");
}
Use the correct keys while opting any data
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
JSONObject jsonObject = new JSONObject(result);
JSONArray jArray = jsonObject.getJSONArray("dados");
Log.i("***2nd JSON ITSELF***", result);
for (int i=0; i<jArray.length(); i++) {
JSONObject jsonObject = new JSONObject(result);
JSONArray jArray = jsonObject.optJSONArray("dados");
Log.i("***2nd JSON ITSELF***", result);
for (int i=0; i<jArray.length(); i++) {
JSONObject jsonPart = jArray.optJSONObject(i);
int id = jsonPart.optInt("Id");
Log.i("***id***", String.valueOf(id));
String chamado = jsonPart.optString("Chamado");
Log.i("***Chamado***", chamado);
String solicitante = jsonPart.optString("Solicitante");
Log.i("***Solicitante***", solicitante);
String itemDeCatalogo = jsonPart.optString("ItemDeCatalogo");
Log.i("***Item de Catalogo***", itemDeCatalogo);
}
}catch(JSONException e) {
e.printStackTrace();
}// END CATCH
}
I wrote a library for parsing and generating JSON in Android
http://github.com/amirdew/JSON
for your sample:
JSON jsonData = new JSON(jsonString);
//access IdChamado of first item:
int IdChamado = jsonData.key("dados").index(0).key("IdChamado").intValue();
//in loop:
JSON dadosList = jsonData.key("dados");
for(int i=0; i<dadosList.count(); i++){
int IdChamado = dadosList.index(i).key("IdChamado").intValue();
String Chamado = dadosList.index(i).key("Chamado").stringValue();
}

JSONArray parsing a multidimensional array

I have an array jArray in the format :
{"users":[
{
"user_id":6,
"user_name":"Ted Vanderploeg",
"email":"test5#test.com",
"additional_info":[["HP","Chief Sales Officer","","",1]]
},
{
"user_id":59,
"user_name":"Lindsay White",
"email":"test12260#test.com",
"additional_info":[["Microsoft","Global Head","","",1]]
}
]
}
Now I need to get the value "Microsoft" from additional_info array. This is what I'm trying :
for(int i=0;i<jArray.length();i++) {
JSONObject jsonObject = new JSONObject(jArray.getString(i));
String workInfo = jsonObject.getString("additional_info");
Log.i("MyActivity", "got work obj as " + workInfo.toString());
}
Now I get workInfo as [["Microsoft","Global Head","","",1]]. Stuck on how to proceed next, to get the value Microsoft.
it looks like a JSONArray inside a JSONArray
for(int i=0;i<jArray.length();i++) {
JSONObject jsonObject = new JSONObject(jArray.getString(i));
JSONArray workinfo = jsonObject.optJSONArray("additional_info");
if (workinfo != null) {
for(int j=0;j<workinfo.length();j++) {
JSONArray values = workinfo.optJSONArray(j);
for(int z=0;z<values.length();z++) {
Log.i("MyActivity", "got work obj as " + values.optString(z));
}
}
}
}

How to get handle json data with two arrays in android?

I want to get two json array from remote url
I am using AsyncTask to do that but i can't get any data !
#Override
protected Void doInBackground(String... params) {
try {
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
String json = jParser.getJSONFromUrl(params[0]);
// Getting Array of Contacts
data = new JSONArray(json);
JSONArray cities = data.getJSONArray();
// looping through All cities
for (int i = 0; i < cities.length(); i++) {
JSONObject e = cities.getJSONObject(i);
String ci_name = e.getString("ct_name");
String ci_web_id = e.getString("ct_id");
db.addCity(ci_name, ci_web_id);
db.closeDatabase();
}
JSONArray districts = data.getJSONArray(1);
// looping through All districts
for (int i = 0; i < districts.length(); i++) {
JSONObject e = districts.getJSONObject(i);
String di_name = e.getString("ar_name");
String di_web_id = e.getString("ar_id");
db.addDistrict(di_name, di_web_id);
db.closeDatabase();
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
The return data is like that :
{"city":[
{"ct_id":"1432","ct_name":"\u062e\u0645\u064a\u0633 \u0645\u0634\u064a\u0637","ct_hide":"0","ct_ord":"0","ct_created":"0"},
{"ct_id":"1434","ct_name":"\u0639\u0633\u064a\u0631","ct_hide":"0","ct_ord":"0","ct_created":"0"},{"ct_id":"1435","ct_name":"\u0627\u0644\u0645\u0646\u0637\u0642\u0629 \u0627\u0644\u0634\u0631\u0642\u064a\u0629","ct_hide":"0","ct_ord":"0","ct_created":"0"}
], "area":[
{"ar_id":"1422","ar_name":"\u0627\u0644\u0645\u062f\u064a\u0646\u0629 \u0627\u0644\u0645\u0646\u0648\u0631\u0647","ar_hide":null,"ar_ord":null,"ar_created":null}, {"ar_id":"1433","ar_name":"\u0646\u062c\u0631\u0627\u0646","ar_hide":null,"ar_ord":null,"ar_created":null}]
}
Your json is a JSONObject not a JSONarray.
This
data = new JSONArray(json);
is wrong.
{ // json object node
"city": [ // json array city
{ // json object
"ct_id": "1432",
"ct_name": "خميس مشيط",
"ct_hide": "0",
"ct_ord": "0",
"ct_created": "0"
},
{
"ct_id": "1434",
"ct_name": "عسير",
"ct_hide": "0",
"ct_ord": "0",
"ct_created": "0"
},
{
"ct_id": "1435",
"ct_name": "المنطقة الشرقية",
"ct_hide": "0",
"ct_ord": "0",
"ct_created": "0"
}
],
"area": [ // json array area
{
"ar_id": "1422",
"ar_name": "المدينة المنوره",
"ar_hide": null,
"ar_ord": null,
"ar_created": null
},
{
"ar_id": "1433",
"ar_name": "نجران",
"ar_hide": null,
"ar_ord": null,
"ar_created": null
}
]
}
To parse
JSONObject jb = new JSONObject(json);
JSONArray city = jb.getJSONArray("city");
for(int i=0;i<city.length();i++)
{
JSONObject jb1 = city.getJSONObject(i);
String id = jb1.getString("ct_id");
String name = jb1.getString("ct_name");
String hide = jb1.getString("ct_hide");
String ord = jb1.getString("ct_ord");
String created = jb1.getString("ct_ord");
Log.i("city id is",id);
}
JSONArray area = jb.getJSONArray("area");
for(int i=0;i<area.length();i++)
{
JSONObject jb1 = area.getJSONObject(i);
String id = jb1.getString("ar_id");
String name = jb1.getString("ar_name");
String hide = jb1.getString("ar_hide");
String ord = jb1.getString("ar_ord");
String created = jb1.getString("ar_ord");
Log.i("Area id is",id);
}
You could also consider using gson to parse json to java objects
http://code.google.com/p/google-gson/
I don't see any request to remote url. How do you get data from your server?
Generally, it looks like this:
public void execute() {
final AndroidHttpClient client = AndroidHttpClient.newInstance("TAG");
try {
HttpUriRequest request = getRequest();
HttpResponse response = client.execute(request);
final int code = response.getStatusLine().getStatusCode();
Log.d("TAG", "Server returns " + code);
if (code == HttpStatus.SC_OK) {
String json = EntityUtils.toString(response.getEntity());
handleResult(json);
}
} catch (IOException e) {
Log.e("TAG", "Failed to execute response", e);
}
}
private void handleResult(String json) {
try {
JSONObject jObject = new JSONObject(json);//your response is not an array
JSONArray content = jObject.getJSONArray("city")
final int count = content.length();
for (int i = 0; i < count; i++) {
JSONObject city = content.getJSONObject(i);
Log.d("TAG", city.getString("ct_id"));
}
} catch (JSONException e) {
Log.e("TAG", "Failed to obtain json", e);
}
}

Categories

Resources