This question already has an answer here:
JSON array parsing in android
(1 answer)
Closed 7 years ago.
I have a JSON response in this format:
{
"success": true,
"categories": [{
"id": "774",
"name": "1"
}, {
"id": "774",
"name": "1"
}]
}
And I am parsing it like this:
try {
JSONObject obj = new JSONObject(response);
String success = String.valueOf(obj.getBoolean("success"));
JSONArray arr = obj.getJSONArray("categories");
//loop through each object
for (int i=0; i<arr.length(); i++) {
JSONObject jsonProductObject = arr.getJSONObject(i);
String name = jsonProductObject.getString("name");
String url = jsonProductObject.getString("id");
Toast.makeText(getApplicationContext(),name, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
But I only get the value of success. What I'm doing wrong here?
Parse as below -
JSONObject obj = new JSONObject(json);
String success = obj.getString("success");
JSONArray arr = obj.getJSONArray("categories");
//loop through each object
for (int i=0; i<arr.length(); i++) {
JSONObject jsonProductObject = arr.getJSONObject(i);
String name = jsonProductObject.getString("name");
String url = jsonProductObject.getString("id");
}
correct json key
JSONArray arr = obj.getJSONArray("checkouts");
replace by:
JSONArray arr = obj.getJSONArray("categories");
DO like this,
if (!result.equalsIgnoreCase("")) {
try {
JSONObject _jsonObject = new JSONObject(result);
boolean json = false;
json = _jsonObject.getBoolean("Status");
JSONArray jsonArray1 = _jsonObject.getJSONArray("categories");
for (int i=0; i<jsonArray1.length(); i++) {
JSONObject jsonObject = jsonArray1.getJSONObject(i);
String name = jsonObject.getString("name");
String id = jsonObject.getString("id");
}
} catch (Exception e) {
Utils.printLoge(5, "error parse json", "--->" + e.getMessage());
return "ERROR";
}
}
Related
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();
}
This question already has answers here:
How do I parse JSON in Android? [duplicate]
(3 answers)
Closed 6 years ago.
I currently have the following JSON structure:
{
"Apps": [
{
"column1": "sample string 1",
"column2": true
},
{
"column1": "sample string 1",
"column2": true
}
],
"param": true
}
How do I get the values of the column1 and column2? What I only know how to parse is a JSONObject within a JSONArray.
JSONObject jSONObject = new JSONObject(yourStrinig);
JSONArray jArray = jSONObject.getJSONArray("Apps");
for (int i = 0; i < jArray.length(); i++) {
JSONObject childrenObject = jArray.getJSONObject(i);
String column1 = childrenObject.getString("column1");
String column2 = childrenObject.getString("column2");
}
Something like this.
// Get a reference to the JSON object
JSONObject jSONObject = new JSONObject(stringJsonResponse);
// Getting the JSON array node
JSONArray jsonAray = jSONObject.getJSONArray("Apps");
// Looping through the json array
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject childrenObject = childrenArray.getJSONObject(i);
...
...
...
}
You can take a look at how I parsed JSON data when I received similar data https://github.com/gSrikar/AskReddit/blob/master/app/src/main/java/com/example/srikar/askreddit/MainActivity.java
with this you can loop through all elements
private void showJSON(String response){
String name="";
String phone_number="";
try {
JSONObject jsonObject =new JSONObject(response);
JSONArray result = jsonObject.getJSONArray(config.JSON_ARRAY);
for(int x=0;x<result.length();x++) {
JSONObject collegeData = result.getJSONObject(x);
name = collegeData.getString(config.KEY_NAME);
phone_number = collegeData.getString(config.KEY_PHONE_NUMBER);
//you can save your data in list here
}
} catch (JSONException e) {
e.printStackTrace();
}
}
I would need help to parse this JSONArray in my Android app. I'm a bit confused with JSONObjects and JSONArrays :
[
{
"nid": [
{
"value": "3"
}
],
"uid": [
{
"target_id": "1",
"url": "/user/1"
}
],
"field_image": [
{
"target_id": "2",
"alt": "alternate 1",
"title": "",
"width": "640",
"height": "640",
"url": "http://url"
},
{
"target_id": "3",
"alt": "alternate 2",
"title": "",
"width": "640",
"height": "640",
"url": "http://url"
}
]
}]
Here is what I've got to start the iteration :
public void onResponse(JSONArray response) {
try {
jsonResponse = "";
for (int i = 0; i < response.length(); i++) {
...
Here is your code to parse data,
private void parseData(){
try {
JSONArray jsonArray=new JSONArray(response);
JSONObject jsonObject=jsonArray.getJSONObject(0);
JSONArray jsonArrayNid=jsonObject.getJSONArray("nid");
JSONArray jsonArrayUid=jsonObject.getJSONArray("uid");
JSONArray jsonArrayField_image=jsonObject.getJSONArray("field_image");
for(int i=0;i<jsonArrayNid.length();i++){
JSONObject jsonObjectNid=jsonArrayNid.getJSONObject(i);
String value=jsonObjectNid.getString("value"); //here you get your nid value
}
for(int i=0;i<jsonArrayUid.length();i++){
JSONObject jsonObjectUid=jsonArrayUid.getJSONObject(i);
String target_id=jsonObjectUid.getString("target_id"); //here you get your uid target_id value
String url=jsonObjectUid.getString("url"); //here you get your uid url value
}
for(int i=0;i<jsonArrayField_image.length();i++){
JSONObject jsonObjectFieldImage=jsonArrayField_image.getJSONObject(i);
String target_id=jsonObjectFieldImage.getString("target_id");
String alt=jsonObjectFieldImage.getString("alt");
String title=jsonObjectFieldImage.getString("title");
String width=jsonObjectFieldImage.getString("width");
String height=jsonObjectFieldImage.getString("height");
String url=jsonObjectFieldImage.getString("url");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
for (int i = 0; i < response.length(); i++) {
JSONObject tobject = response.getJSONObject(i);
JSONArray nid = tobject.getJSONArray("nid");
JSONArray uid= tobject.getJSONArray("uid");
JSONArray field_image= tobject.getJSONArray("field_image");
//similarly you can loop inner jsonarrays
}
Use code according to you:
JSONArray array = null;
try {
array = new JSONArray(url); // your web url
JSONObject object = array.getJSONObject(0);
JSONArray array1 = object.getJSONArray("nid");
JSONObject object1 = array1.getJSONObject(0);
String value = object1.getString("value");
JSONArray array2 = object.getJSONArray("uid");
JSONObject object2 = array2.getJSONObject(0);
String target = object2.getString("target_id");
String url = object2.getString("url");
JSONArray array3 = object.getJSONArray("field_image");
JSONObject object3 = array3.getJSONObject(0);
String alt = object3.getString("alt");
Toast.makeText(Testing.this,value+"\n"+target+"\n"+url+"\n"+alt,Toast.LENGTH_LONG).show();
} catch (JSONException e) {
e.printStackTrace();
}
Try to parse like this.
In this code, jsonArray is the parent array which you have in your JSON.
for(int i=0;i<jsonArray.length();i++)
{
try {
JSONObject object=jsonArray.getJSONObject(i);
JSONArray imageArray=object.getJSONArray("field_image");
for(int j=0;j<imageArray.length();j++)
{
JSONObject imageObject=imageArray.getJSONObject(j);
String targetId=imageObject.getString("target_id");
}
}
catch (JSONException e) {
e.printStackTrace();
}
}
Now :) if you have to parse something first look for some library:
http://www.java2s.com/Code/Jar/g/Downloadgson222jar.htm
Download gson.jar and then create java classes that mimic your desired json:
class C1{
private String value;
}
class C2{
private String target_id;
private String url;
}
class C3{
private String target_id;
private String alt;
private String title;
private String width;
private String height;
private String url;
}
class c4{
private List<C1> nid;
private List<C2> uid;
private List<C3> field_image;
}
Since you receive array from C4, you parse it like this:
public void onResponse(JSONArray response){
String value = response.toString();
GsonBuilder gb = new GsonBuilder();
Type arrayType = new TypeToken<List<C4>>() {}.getType();
List<C4> data = gb.create().fromJson(value, arrayType);
}
So in just 3 lines of code, you have your entire json serialized to java objects that you can use in your code.
Try
public void onResponse(JSONArray response) {
try {
if (response != null) {
for (int i = 0; i < response.length(); i++) {
JSONObject jsonObject = resultsArray.getAsJsonObject(i);
//get nid array
JSONArray nidJSONArray = jsonObject.getJSONArray("nid");
//get uid array
JSONArray uidJSONArray = jsonObject.getJSONArray("uid");
//get field_image array
JSONArray fieldImageJSONArray = jsonObject.getJSONArray("field_image");
//parse nid array
if (nidJSONArray != null) {
for (int i = 0; i < nidJSONArray.length(); i++) {
JSONObject jsonObject = nidJSONArray.getAsJsonObject(i);
String value = jsonObject.getString("value");
}
}
//parse uid array
if (uidJSONArray != null) {
for (int i = 0; i < uidJSONArray.length(); i++) {
JSONObject jsonObject = uidJSONArray.getAsJsonObject(i);
String targetId = jsonObject.getString("target_id");
String url = jsonObject.getString("url");
}
}
//parse field_image array
if (fieldImageJSONArray != null) {
for (int i = 0; i < fieldImageJSONArray.length(); i++) {
JSONObject jsonObject = fieldImageJSONArray.getAsJsonObject(i);
String targetId = jsonObject.getString("target_id");
String alt = jsonObject.getString("alt");
String title = jsonObject.getString("title");
String width = jsonObject.getString("width");
String height = jsonObject.getString("height");
String url = jsonObject.getString("url");
}
}
}
}
} catch(Exception e) {
Log.e("Error", e.getMessage());
}
}
I have string json like this :
{
"listResult": {
"items": [
{
"id": "629047db-66d9-4986-ba3f-c75554198138",
"thumbnail": "http://maya-wdv-01.r.worldssl.net/39aa32db-6f50-4da1-8fd5-a5b001135b98/629047db-66d9-4986-ba3f-c75554198138/8cb69c17-0fdb-454c-bfb5-a5b9001a9d59.jpg"
},
{
"id": "fa872dc8-d2b3-4815-92ef-d90e903bc3d8",
"thumbnail": "http://maya-wdv-01.r.worldssl.net/39aa32db-6f50-4da1-8fd5-a5b001135b98/fa872dc8-d2b3-4815-92ef-d90e903bc3d8/c510c24f-5bfd-4a64-8851-a5b90017a38d.jpg"
}
],
"totalItems": 34,
"pageSize": 5,
"pageNumber": 1,
"totalPages": 7,
"searchTerm": null
}
}
I Try Parsing with code :
try {
JSONObject json = new JSONObject(response);
String listResult = json.getString(Variabel.listResult);
JSONArray items_obj = json.getJSONArray(Variabel.items);
int jumlah_list_data = items_obj.length();
if (jumlah_list_data > 0) {
for (int i = 0; i < jumlah_list_data; i++) {
JSONObject obj = items_obj.getJSONObject(i);
String id = obj.getString(Variabel.id);
String thumbnail = obj.getString(Variabel.thumbnail);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
But I getting Error :
org.json.JSONException: No value for items
So how to solve it ? sorry for my English
Instead of:
JSONObject json = new JSONObject(response);
String listResult = json.getString(Variabel.listResult);
JSONArray items_obj = json.getJSONArray(Variabel.items);
you should have:
JSONObject json = new JSONObject(response);
JSONObject listResult = json.getJSONObject(Variabel.listResult);
JSONArray items_obj = listResult.getJSONArray(Variabel.items);
Accordingly to the json you posted, items is direct child of listResult, so you have to use the JSONObject with key listResult to retrieve it. Change
JSONArray items_obj = json.getJSONArray(Variabel.items);
with
JSONArray items_obj = listResult.getJSONArray(Variabel.items);
This question already has answers here:
How to parse JSON in Java
(36 answers)
Closed 7 years ago.
{
"response":
{
"Category":
[
"Restaurant",
"Salon",
"Spa",
"Dry Cleaners",
"Car Spa",
"Hospitals"
]
}
}
You can do like this-
try {
String json = <Your Json String>;
JSONObject response = new JSONObject(json);
JSONArray category = response.getJSONArray("Category");
for (int i = 0; i < category.length(); i++) {
Log.d("categories are", category.getString(i));
}
} catch (JSONException e) {
e.printStackTrace();
}
Try this , it can be Pseudo Code
String json = <YourJSon String>
JSONObject object = new JSONObject(json);
JSONArray array = object.getJSONArray("Category");
for(int i =0; i<array.size();i++){
String s = array.get(i).getString();
}