Access Nested JSON Android - 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();
}

Related

How to get some string from JsonObject?

I got from server response by retrofit, that is actually JsonObject(using Gson):
{"a": "a and its content 1", "b": [{"b_1": "string: b_1", "b_2": 2222}]}
so that I get it like this:
JsonObject jsonObject = response.body();
And then I can log it:
Log.d(TAG, jsonObject.get("a")+"");
// log: "a and its content 1"
question:
How can I log only "string: b_1"? (from "b_1": "string: b_1")
As it is in array [], hard to get it for me.
Try this one work for me,
try {
JSONObject jsonObject = response.body();
JSONArray jsonArray = jsonObject.getJSONArray("b");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObj = jsonArray.getJSONObject(i);
String b_1 = jsonObj.getString("b_1");
int b_2 = jsonObj.getInt("b_2");
}
} catch (JSONException e) {
e.printStackTrace();
}
try this
try{
JsonObject jsonObject = response.body();
JSONArray a = jsonObject.getJSONArray("b")
for (int i = 0; i < a.length(); i++) {
Log.d("Type", a.getString(i));
}
}catch(Exception e){
}
Try like below
JSONObject jObj = response.body();
JSONArray jsonArray = jObj.getJSONArray("b");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
Log.d(TAG, jsonObject.getString("b_1")+"");
Log.d(TAG, jsonObject.getInt("b_2")+"");
}
try this
JSONObject jsonObject = new JSONObject(responseString);
String status = String.valueOf(jsonObject.get("a"));

how to parse json array in a json object response?

Iwant to access a jsonArray data in a jsonObjet response code that comes from server. here is my response json
{
event_id: "32",
event_title: "امیر",
event_description: "تست امیر",
event_image: "2_1550507094.jpg",
event_hikers_amount: "9",
event_private: "0",
event_date_start: "17/2/2019",
event_date_end: "21/2/2019",
event_time_start: "21:54",
event_time_end: "12:54",
event_locations_array:
"[
{"latitude":37.58728984572849,"longitude":45.10016608983278},
{"latitude":37.57651702299841,"longitude":45.0880378112197},
{"latitude":37.5753956777439,"longitude":45.1045374199748},
{"latitude":37.564077382844964,"longitude":45.094508975744255},
{"latitude":37.55829758877768,"longitude":45.08105669170619},
{"latitude":37.53919984571198,"longitude":45.09874418377876}
]",
event_latitude_location: "37.587289845728",
event_longitude_location: "45.100166089833",
event_status: "1",
event_users_id: "2"
}
I want to parse "event_locations_array" and what what i done :
#Override
protected void onPostExecute(String result) {
try {
JSONObject jsonObject = new JSONObject(result);
description = jsonObject.getString("event_description");
people_joined = jsonObject.getString("event_hikers_amount");
date_start = jsonObject.getString("event_date_start");
date_end = jsonObject.getString("event_date_end");
time_start = jsonObject.getString("event_time_start");
time_end = jsonObject.getString("event_time_end");
privacy = jsonObject.getString("event_private");
JSONArray jsonArray = jsonObject.getJSONArray("event_locations_array");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject points = jsonArray.getJSONObject(i);
JSONObject lat = points.getJSONObject("latitude");
JSONObject lang = points.getJSONObject("longitude");
}
setTextView();
} catch (JSONException e) {
e.printStackTrace();
}
}
here i can't take that jsonArray. what i did wrong here let me know . I'm a little confused
thanks in advance
Fast solution
If you can not change the JSON generation, simply use this code:
#Override
protected void onPostExecute(String result) {
try {
JSONObject jsonObject = new JSONObject(result);
description = jsonObject.getString("event_description");
people_joined = jsonObject.getString("event_hikers_amount");
date_start = jsonObject.getString("event_date_start");
date_end = jsonObject.getString("event_date_end");
time_start = jsonObject.getString("event_time_start");
time_end = jsonObject.getString("event_time_end");
privacy = jsonObject.getString("event_private");
// 1 - fix string to array conversion
JSONArray jsonArray = new JSONArray(jsonObject.getString("event_locations_array"));
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject points = jsonArray.getJSONObject(i);
// 2 - the fields as double
double lat = points.getDouble("latitude");
double lang = points.getDouble("longitude");
}
setTextView();
} catch (JSONException e) {
e.printStackTrace();
}
}
Detailed solution
There are two errors:
The event_locations_array : "[[{"latitude":37.58728984572849].." contains a string. For the value that it's contains I think it must be generated as array (without the initial and final ")
After fix the first problem, you are trying to extract as object the properties latitude and longitude, but they are attributes. So change in your code:
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject points = jsonArray.getJSONObject(i);
JSONObject lat = points.getJSONObject("latitude");
JSONObject lang = points.getJSONObject("longitude");
}
With
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject points = jsonArray.getJSONObject(i);
double lat = points.getDouble("latitude");
double lang = points.getDouble("longitude");
}
To get Values of event_locations_array use following code:
JSONArray jsonArray = jsonResponse.getJSONArray("event_locations_array");
for (int i=0; i<jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String latitude = jsonObject.getString("latitude");
String longitude = jsonObject.getString("longitude");
}

Android : parse a JSONArray

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());
}
}

JSON array not being parsed [duplicate]

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";
}
}

How do I pull the string array from this json object?

I am trying to get a list of available numbers from the following json object, using the class from org.json
{
"response":true,
"state":1,
"data":
{
"CALLERID":"81101099",
"numbers":
[
"21344111","21772917",
"28511113","29274472",
"29843999","29845591",
"30870001","30870089",
"30870090","30870091"
]
}
}
My first steps were, after receiving the json object from the web service:
jsonObj = new JSONObject(response);
jsonData = jsonObj.optJSONObject("data");
Now, how do I save the string array of numbers?
use:
jsonObj = new JSONObject(response);
jsonData = jsonObj.optJSONObject("data");
JSONArray arrJson = jsonData.getJSONArray("numbers");
String[] arr = new String[arrJson.length()];
for(int i = 0; i < arrJson.length(); i++)
arr[i] = arrJson.getString(i);
you need to use JSONArray to pull data in an array
JSONObject jObj= new JSONObject(your_json_response);
JSONArray array = jObj.getJSONArray("data");
Assuming that you are trying to get it in a javascript block, Try something like this
var arrNumber = jsonData.numbers;
My code is for getting "data":
public void jsonParserArray(String json) {
String [] resultsNumbers = new String[100];
try {
JSONObject jsonObjectGetData = new JSONObject(json);
JSONObject jsonObjectGetNumbers = jsonObjectGetData.optJSONObject("results");
JSONArray jsonArray = jsonObjectGetNumbers.getJSONArray("numbers");
for (int i = 0; i < jsonArray.length(); i++) {
resultsNumbers[i] = jsonArray.getString(i);
}
} catch (JSONException e) {
e.printStackTrace();
Log.e(LOG_TAG, e.toString());
}
}

Categories

Resources