nested JSON object inside JSON array - android

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

Related

I want to get two jsonArray from one url by using String Request

private void loadCricketPlayer() {
//getting the progressbar
final ProgressBar cricketProgressBar = findViewById(R.id.cricketProgressBar);
//making the progressbar visible
cricketProgressBar.setVisibility(View.VISIBLE);
StringRequest stringRequest = new StringRequest(Request.Method.GET, url_new,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
cricketProgressBar.setVisibility(View.INVISIBLE);
try {
//getting the whole json object from the response
JSONObject obj = new JSONObject(response);
JSONArray jArray = obj.getJSONArray("squad");
for (int i = 0; i < jArray.length(); i++) {
JSONObject jsonObject = jArray.getJSONObject(i);
JSONArray bArray = obj.getJSONArray("players");
for (int j = 0; j < bArray.length(); j++){
JSONObject jsonObject1 = bArray.getJSONObject(j);
cricket_Player_POJO cricketPlayer = new cricket_Player_POJO(jsonObject1.getString("name"));
cricketListItem.add(cricketPlayer);
}
}
cricket_Player_List cricketList = new cricket_Player_List(cricketListItem, getApplicationContext());
cricketPLayerlistView.setAdapter(cricketList);
} catch (JSONException e) {
e.printStackTrace();
}
}
},new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//displaying the error in toast if occurrs
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
this is my json Array data for fetching the data from the server
This is my JSONARRAY example. For fetching the data:
{
"squad": [
{
"name": "Australia",
"players": [
{
"pid": 7252,
"name": "Tim Paine"
},
{
"pid": 489889,
"name": "Pat Cummins"
},
{
"pid": 5334,
"name": "Aaron Finch"
},
]
}]
}
How can I Fetch this code Help me How can I do it I am using volley for this and I want to fetch this data in the listview android
How can I Fetch this code Help me How can I do it I am using volley for this and I want to fetch this data in the listview android
replace with this code
try {
//getting the whole json object from the response
JSONObject obj = new JSONObject(response);
JSONArray jArray = obj.getJSONArray("squad");
for (int i = 0; i < jArray.length(); i++) {
JSONObject jsonObject = jArray.getJSONObject(i);
JSONArray bArray = jsonObject.getJSONArray("players");
for (int j = 0; j < bArray.length(); j++){
JSONObject jsonObject1 = bArray.getJSONObject(j);
cricket_Player_POJO cricketPlayer = new cricket_Player_POJO(jsonObject1.getString("name"));
cricketListItem.add(cricketPlayer);
}
}
cricket_Player_List cricketList = new cricket_Player_List(cricketListItem, getApplicationContext());
cricketPLayerlistView.setAdapter(cricketList);
} catch (JSONException e) {
e.printStackTrace();
}

How to get json object and array values?

How to parse JSON values in this format? I want to get the details of the data element but inside data there are 'dates' and inside dates there is array containing two more elements. I want to get all the dates first inside data and then within these dates I want all the information within these dates. How can I achieve this? Please Help. I tried with below code but it hasn't worked
try {
JSONObject jsonObject = new JSONObject("data");
JSONArray jsonArray =jsonObject.getJSONArray(String.valueof(cuurentdate));
JSONArray session;
for (int i = 0; i < jsonArray.length() - 1; i++) {
jsonObject = jsonArray.getJSONObject(i);
session= jsonObject.getJSONArray("session");
Log.d("MyLog", session + "");
}
} catch (JSONException e) {
e.printStackTrace();
}
Following is the format
{
"status": 1,
"status_code": 200,
"data": {
"2018-02-11": [
{
"session": "01:00 AM",
"place": true
},
{
"session": "02:00 AM",
"place": true
}
],
"2018-02-12": [
{
"session": "01:00 AM",
"place": true
},
{
"session": "02:00 AM",
"place": true
}
]
}
}
You just need to pass the response string to the method. You can try this:
private void jsonParsing(String jsonString) {
// String jsonString = "{ \"status\": 1, \"status_code\": 200, \"data\": { \"2018-02-11\": [ { \"session\": \"01:00 AM\", \"place\": true }, { \"session\": \"02:00 AM\", \"place\": true } ], \"2018-02-12\": [ { \"session\": \"01:00 AM\", \"place\": true }, { \"session\": \"02:00 AM\", \"place\": true } ] } }";
try {
JSONObject jsonObject = new JSONObject(jsonString);
JSONObject dataObj = jsonObject.getJSONObject("data");
Iterator<String> iter = dataObj.keys();
Log.e(TAG, "jsonParsing: "+iter );
while (iter.hasNext()) {
String key = iter.next();
JSONArray datesArray = dataObj.getJSONArray(key);
ArrayList<String> sessions = new ArrayList<String>();
for (int i = 0; i < datesArray.length(); i++) {
JSONObject datesObject = datesArray.getJSONObject(i);
sessions.add(datesObject.getString("session"));
}
Log.d("MyLog", sessions + "");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
(1) get JSONObject of Main json
JSONObject objMain = new JSONObject("your json string");
(2)get JSONObject of "data" from main json
JSONObject jsonData = objMain.getJSONObject("data")
(3) get all keys (dates) from object "data"
Iterator<String> iter = jsonData.keys();
while (iter.hasNext()) {
String key = iter.next();
try {
JSONArray arrayDate = objData.getJSONArray(key)
for (i = 0; i < arrayDate.length(); i++) {
JSONObject objDate = arrayDate.getJSONObject(i)
Log.d("#session :", "" + objDate.getString("session"))
Log.d("#place :", "" + objDate.getBoolean("place"))
}
} catch (JSONException e) {
// Something went wrong!
}
}
try this one code
IN THIS CODE jsonMstObject IS TEMP OBJECT YOU HAVE TO USE YOUR API RESPONSE JSONobject INSTEAD OF jsonMstObject
try {
JSONObject jsonMstObject = new JSONObject("{"status":1,"status_code":200,"data":{"2018-02-11":[{"session":"01:00 AM","place":true},{"session":"02:00 AM","place":true}],"2018-02-12":[{"session":"01:00 AM","place":true},{"session":"02:00 AM","place":true}]}}");
JSONObject jsonObject = jsonMstObject.getJSONObject("data");
JSONArray jsonArray =jsonObject.getJSONArray(String.valueof(cuurentdate));
ArrayList<String> arrSession = new ArrayList<String>();
for (int i = 0; i < jsonArray.length(); i++) {
jsonObject = jsonArray.getJSONObject(i);
arrSession.add(jsonObject.getString("session"));
}
Log.d("MyLog", arrSession + "");
} catch (JSONException e) {
e.printStackTrace();
}
in this code arrSession is your session string array
Ex. you passed cuurentdate = "2018-02-11" then you recived result like
[01:00 AM, 02:00 AM]
Note: this code is worked based on your cuurentdate param. This is code for get static date array from data and create String Array.

java.lang.String cannot be converted to JSONObject. mismatch type

JSON Array
[
{
"0": {
"program_name": "Daycare"
},
"1": {
"program_name": "Preschool"
},
"program_name": [
{
"program_name": "Daycare"
},
{
"program_name": "Preschool"
}
],
"batch_name": [
{
"0": "3 Hours",
"batch_class_name": "3 Hours"
},
{
"0": "5 Hours",
"batch_class_name": "5 Hours"
}
]
}
]
This is what I've done so far: -
void getProgram() {
progressDialog = new MaterialDialog.Builder(getActivity())
.content("Please wait....")
.progress(true, 0)
.show();
StringRequest stringRequest = new StringRequest(Request.Method.POST, GlobalConfig.GET_PROGRAM_AND_BATCH_OF_TEACHER,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
progressDialog.dismiss();
Log.e("response", response);
try {
JSONArray jsonArray = new JSONArray(response);
JSONObject jsonObject = jsonArray.getJSONObject(0);
JSONArray jsonProgramArray = jsonObject.getJSONArray("program_name");
for (int i = 0; i < jsonObject.length() - 1; i++) {
BatchModel programe = new BatchModel();
programe.setTitle(jsonProgramArray.getString(i));
programe.setId(jsonProgramArray.getString(i));
programlist.add(programe);
Log.e("Program test", programlist.toString());
}
} catch (JSONException e) {
e.printStackTrace();
I want to add to list strings of "program_name" which is mark in bold:
But I'm getting this error:
#user3885363 .you try this.
JSONArray jsonArray = new JSONArray(response);
JSONObject jsonObject = jsonArray.getJSONObject(0);
JSONArray jsonProgramArray = jsonObject.getJSONArray("program_name");
for (int i = 0; i < jsonProgramArray.length(); i++) {
JSONObject jsonObjectnew = jsonProgramArray.getJSONObject(i);
BatchModel programe = new BatchModel();
programe.setTitle(jsonObjectnew.getString("program_name"));
programlist.add(programe);
Log.e("Program test", programlist.toString());
}
you are using jsonObject.length() in your loop for (int i = 0; i < jsonObject.length() - 1; i++) but you have your program_name in the array you just get from object. JSONArray jsonProgramArray = jsonObject.getJSONArray("program_name");. Try to loop on jsonProgramArray and get the program_name object for each program.
JSONArray jsonArray = new JSONArray(response);
// Here you are getting the program JSONArray
JSONArray jsonProgramArray = jsonArray.getJSONArray("program_name");
for (int i = 0; i < jsonProgramArray.length() - 1; i++) {
// Get the each Json Object from the Array
JSONObject jsonProgramObject = jsonProgramArray.getJSONObject(i);
String program_name = jsonProgramObject.getString("program_name")
}
You can do the same thing for the other batch_name array
You have 2 "program_name" one is string inside jsonObject "0" to get that you have to do like this
JSONArray jsonArray = new JSONArray(response);
JSONObject jsonObject = jsonArray.getJSONObject(0);
JSONObject jsonObjt_0 = jsonObject.getJSONObject("0");
String productName = jsonObjt_0.getString("program_name")
Then you have a jsonArray named "program_name" to get that do like this.
JSONArray productArray = jsonObject.getJSONArray("program_name");
for (int i = 0; i < productArray .length(); i++) {
JSONObject listItem = productArray.getJSONObject(i);
BatchModel programe = new BatchModel();
programe.setTitle(listItem.getString("program_name"));
programe.setId(listItem.getString("program_name"));
programlist.add(programe);
}
PS. This is a weird json, consider changing the json with some meanigful names,Please don't use the same name for everything..

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

Android parsing json

Im getting problems with parsing Json.
my json response.
{
"Persons": [
{
"id": 0,
"name": "William",
"image": "http://www.images-image2312321356.jpg",
"colors": [
"White",
"Red",
"Green"
]
},
{...}
Im trying this. but it causes a compile error
public void onResponse(JSONObject responseObject) {
try {
JSONArray rs = responseObject.getJSONArray("Persons");
for (int i = 0; i < rs.length(); i++) {
try {
final JSONObject c = rs.getJSONObject(i);
String name = c.getString("name");
items.add(name);
));
}
} catch (JSONException e) {
e.printStackTrace();
}
Any idea? Im using volley
public void onResponse(JSONObject responseObject) {
JSONArray rs = responseObject.getJSONArray("Persons");
if (rs != null || rs.length() > 0) {
for (int i = 0; i < rs.length(); i++) {
JSONObject obj = rs.getJSONObject(i);
String id = obj.getString("id");
String name = obj.getString("name");
String img = obj.getString("image");
JSONArray colors = obj.getJSONArray("colors");
for (int ii = 0; ii < colors.length(); ii++) {
String color = colors.getString(ii);
colors.add(color);
}
}
}
}

Categories

Resources