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());
}
}
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();
}
I'm trying to parse a JSON object. The JSON response is as follows.
{
"message": "Success",
"list": [
{
"orderId": 24,
"phoneNumber": "1234567893",
"totalAmount": 100,
"addressBean": {
"cadId": 1,
"phone2": "1234567899",
"address1": "34, gandhi nagar",
}
},
Android code which i have tried for getting "orderId", "phoneNumber" and "totalAmount" is below.
final List<OrderModel> orderList = new ArrayList<>();
public void onResponse(JSONObject response) {
try {
if (response.getString("message").equalsIgnoreCase("Success")) {
JSONArray jArray = response.getJSONArray("list");
for (int i = 0; i < jArray.length(); i++) {
OrderModel model = new OrderModel();
orderModel.setOrderId(jArray.getJSONObject(i).getString("orderId"));
orderModel.setphoneNumber(jArray.getJSONObject(i).getString("phoneNumber"));
orderModel.setTotalAmount(new BigDecimal(jArray.getJSONObject(i).getString("totalAmount")));
orderList.add(orderModel);
}
setOrderList(orderList);
I want to show the "cadId", "phone2" and "address1" in a Textview. How can i do that?
Try to use this Code
try {
JSONArray jArray = response.getJSONArray("list");
for (int i = 0; i < jArray.length(); i++) {
JSONObject jsonObject = jArray.getJSONObject(i);
if (jsonObject.has("addressBean")){
JSONObject addressObject = jsonObject.getJSONObject("addressBean");
int cadId = addressObject.getInt("cadId");
String phone = addressObject.getString("phone2");
String address = addressObject.getString("address1");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
Code for phone2
String phone2 = jArray.getJSONObject(i).getJSONObject("addressBean").getString("phone2");
Use getInt() for cadId
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";
}
}
i have get the first array of json but the second array come inside the first array in array ....:
how is solved it
i have get the tweet_image array inside the image array two array how is solve it
i have get the image path;
{
"feed": [
{
"tweet_id": "794",
"userid": "6",
"content": "<a href=http://www.punjabkesari.in/news/article-370994>http://www.punjabkesari.in/news/article-370994</a>",
"favorite_count": "0",
"reply_count": "0",
"retweet_count": "0",
"tweet_location": "",
"created_date": "2015-06-16 11:49:00",
"name": "amar bhanu",
"user_image": "http://sabakuch.com/public/images_upload/avatars/ozone/6_30_imageamar.jpg",
"tweet_images": {
"image": [
"http://sabakuch.com/public/images_upload/tweet/794_400_1434435540_album143443554069.jpg"
]
}
}
]
}
You can try this.
try {
JSONObject _jObject = new JSONObject("YOUR_JSON_STRING");
JSONArray _jArrayFeed = _jObject.getJSONArray("feed");
if (_jArrayFeed.length()>0) {
for (int i = 0; i < _jArrayFeed.length(); i++) {
JSONObject _subObj = _jArrayFeed.getJSONObject(i);
String _tweet_id = _subObj.getString("tweet_id");
String _userid = _subObj.getString("userid");
String _content = _subObj.getString("content");
String _favorite_count = _subObj.getString("favorite_count");
String _reply_count = _subObj.getString("reply_count");
String _retweet_count= _subObj.getString("retweet_count");
String _tweet_location = _subObj.getString("tweet_location");
String _created_date = _subObj.getString("created_date");
String _name = _subObj.getString("name");
String _user_image = _subObj.getString("user_image");
JSONObject _jObjtweet_images = _subObj.getJSONObject("tweet_images");
JSONArray _jArrayImages = _jObjtweet_images.getJSONArray("image");
if (_jArrayImages.length()>0) {
for (int j = 0; j < _jArrayImages.length(); j++) {
String _image = _jArrayImages.getString(j);
}
}
}
}
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
And let me know, if you have any issues.
Try this way
JSONArray array= jsonResponse.getJSONArray("feed");
JSONObject obj= array.getJSONObject(0);
JSONObject image= obj.getJSONObject("tweet_images");
JSONArray image_array= image.getJSONArray("image");
String url= image_array.getString(0);
hope it helps :-)
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);
}
}