I have nested json array in below format.I am using volley liabrary for JSON Parsing.
{
"City": [{
"name": "Mumbai",
"Mumbai": [{
"area": "andheri",
"diler": [{
"DName": "yuvraj"
}]
}, {
"area": "jogeshwari"
}, {
"area": "goregaon"
}]
},
{
"name": "Nashik",
"Nashik": [{
"area": "clg rd",
"diler": [{
"DName": "yuvraj"
}]
}, {
"area": "GP RD",
"diler": [{
"DName": "Roshan"
}]
}, {
"area": "CBS",
"diler": [{
"DName": "Deepak"
}]
}]
}, {
"name": "Bengaluru"
}
]}
Below is the code which i have write in android.
jsonURL = "http://192.168.1.11/cycle_webservices/testing.json";
buttonReq.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(
jsonURL,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
for (int i = 0; i < response.length(); i++) {
JSONObject jsonObject = response.getJSONObject(i);
String name = jsonObject.getString("name");
String area = jsonObject.getString("area");
String diler = jsonObject.getString("diler");
textView.append("\nCity: " + name + "\nArea: " + area + "\nDealer: " + diler + "\n");
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("VOLLEY", "ERROR");
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
}
}
);
requestQueue.add(jsonArrayRequest);
}
});
But i am getting Errors while parsing it in Android.
The error is- JSONObject can not be converted to JSONArray
Can anyone please provide sample code to parse this json Array.
Thanks in Advance
Here is your problem solution, use below code
try {
JSONObject jsonObject = new JSONObject("response");
JSONArray jsonArray = jsonObject.getJSONArray("City");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
String name = object.getString("name");
if (object.length() != 0) {
Iterator<String> key = object.keys();
while (key.hasNext()) {
String cityname = key.next();
JSONArray ja = object.getJSONArray(cityname);
for (int j = 0; j < ja.length(); j++) {
JSONObject object1 = ja.getJSONObject(j);
String area = object1.getString("area");
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
And try to make your JSON format same.
The point is the first json node is a JsonObject,
change your code this way and continue parsing:
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Use JSONObject for parsing data like:
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("City");
for(int i = 0; i<jsonArray.length(); i++)
{
JSONObject jsonObject = jsonArray .getJSONObject(i);
String name = jsonObject.getString("name");
JSONArray city_array = jsonObject.getJSONArray(name);
for(int j=0; j<city_array.length(); j++)
{
JSONObject obj = city_array.getJSONObject(j);
String area = obj.getString("area");
JSONArray diler_array = obj.getJSONArray("diler");
JSONObject obj1 = diler_array.getJSONObject(0);
String DName = obj1.getString("DName");
}
}
Please check edited answer.
pass data array inside array in android using volley
public List<HashMap<String,String>> returnJsonforPhp(){
HashMap<String,String> map = new HashMap<String,String>();
List<HashMap<String,String>> forjson= new ArrayList<HashMap<String,String>>();
/*for(int i=0;i<dblist;i++) {
map.put("name",dblist.getName());
map.put("email",dblist.getEmail());
map.put("mobno",dblist.getMobno());
forjson.add(map);
}*/
map.put("name","ravi");
map.put("email","ravi#gmail.com");
map.put("mobno","9897939595");
forjson.add(map);
return forjson;
}
String OTP_Url = "https://www.yourdomain.com/rest/updateregistration/";
public String getJson() throws JsonProcessingException {
List> list = new ArrayList>();
List>> newlist = new ArrayList>>();
newlist.add(list);
HashMap<String,String> map = new HashMap<String, String>();
map.put("name","knnkl");
map.put("email","kjbjbk");
map.put("password","njnjknk");
list.add(map);
newlist.add(list);
String parsedJson = new ObjectMapper().writeValueAsString(newlist);//json conversion
return parsedJson;
}
compile (
[group: 'com.fasterxml.jackson.core', name: 'jackson-core', version: '2.4.1'],
[group: 'com.fasterxml.jackson.core', name: 'jackson-annotations', version: '2.4.1'],
[group: 'com.fasterxml.jackson.core', name: 'jackson-databind', version: '2.4.1']
)
Related
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 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.
Hi i was trying to parse a json array inside another json array. Help me with this.
my Json Array is
"results":[
{
"percentcompleted":0,
"requirers":[
{
"activityContext":null,
"auditReason":null,
"assignee":{
"sourceType":"InternalPerson",
"activitySourceType":{
"listId":"sysli000000000003037",
"sourceType":0,
"key":"0",
"displayName":"Person"
},
"locale":{
"id":"local000000000000001",
"displayName":"English"
},
"id":"emplo000000006156648",
"displayName":"Venkat Rao"
},
"targetDate":null,
"assignment":{
"id":"stcur000000000003182",
"displayName":null
},
"learningEvent":{
"id":"curra000000000003001",
"displayName":"Studieplan_test för OKQ8"
},
"jobTypeId":null,
"listIds":null,
"assignedOn":1502084325000,
"source":{
"sourceType":"InternalPerson",
"activitySourceType":{
"listId":"sysli000000000003037",
"sourceType":0,
"key":"0",
"displayName":"Person"
},
"locale":{
"id":"local000000000000001",
"displayName":"English"
},
"id":"emplo000000006156648",
"displayName":"Venkat Rao"
},
"required":true,
"actions":null,
"id":"currh000000000014343"
}
],
"basicdetail":{
"revokedOn":null,
"need_recert":false,
"curriculum":{
"id":"curra000000000003001",
"displayName":"Studieplan_test för OKQ8"
},
"recert_window_starts_on":null,
"createdBy":"vrao",
"updatedBy":"vrao",
"createdOn":1502084325000,
"updatedOn":1508357353000,
"status":{
"intStatus":400,
"description":"Assigned",
"displayName":"Assigned"
},
"type":"CURRICULUM",
"path":{
"id":"track000000000003081",
"displayName":"Studieplan"
},
"acquiredOn":null,
"assignee":{
"sourceType":"InternalPerson",
"activitySourceType":{
"listId":"sysli000000000003037",
"sourceType":0,
"key":"0",
"displayName":"Person"
},
"locale":{
"id":"local000000000000001",
"displayName":"English"
},
"id":"emplo000000006156648",
"displayName":"Venkat Rao"
},
"targetDate":null,
"startedOn":null,
"assignedOnDate":1502084325000,
"heldCertNo":"00003787",
"owner":{
"sourceType":"InternalPerson",
"activitySourceType":{
"listId":"sysli000000000003037",
"sourceType":0,
"key":"0",
"displayName":"Person"
},
"locale":{
"id":"local000000000000001",
"displayName":"English"
},
"id":"emplo000000006156648",
"displayName":"Venkat Rao"
},
"id":"stcur000000000003182",
"assigneeAdditionalDetails":{
"person_no":"VRAO",
"username":"VRAO"
}
},
"isgranted":null
},
and my Code to parse the above data is
public class CurriculaParser {
public ArrayList<CurriculaData> getData(String response)
{
ArrayList<CurriculaData> dataList = new ArrayList<>();
try {
JSONObject mainObj = new JSONObject(response);
JSONArray array = mainObj.getJSONArray("results");
CurriculaData data;
for(int i = 0;i<array.length();i++)
{
data = new CurriculaData();
JSONObject resObj = array.getJSONObject(i);
JSONArray reqArray = resObj.getJSONArray("requires");
for( int j =0;j<reqArray.length();j++) {
JSONObject reqObj = reqArray.getJSONObject(j);
JSONObject innerObj = reqObj.getJSONObject("learningEvent");
data.setTitle(innerObj.getString("displayName"));
data.setAssignedOn(reqObj.getString("assignedOn"));
}
JSONArray basicDetailArray = resObj.getJSONArray("basicdetail");
for(int k=0;k<basicDetailArray.length();k++) {
JSONObject basicDetailObj = basicDetailArray.getJSONObject(k);
JSONObject statusObj = basicDetailObj.getJSONObject("status");
data.setStatus(statusObj.getString("displayName"));
data.setAcquiredOn(basicDetailObj.getString("acquiredOn"));
JSONObject assignObj = basicDetailObj.getJSONObject("assignee");
data.setAssignedBy(assignObj.getString("displayName"));
}
dataList.add(data);
}
} catch (Exception e) {
e.printStackTrace();
}
return dataList;
}
and finally i got error like
org.json.JSONException: No value for requires
let me know the error what i made and iam a beginner in dealing with jsonarray inside another jsonarray
org.json.JSONException: No value for requires
JSONException
KEY mismatches on lookups
You should pass requirers instead of requires.
JSONArray reqArray = resObj.getJSONArray("requirers");
fixed the requires TYPO error
public class CurriculaParser {
public ArrayList<CurriculaData> getData(String response)
{
ArrayList<CurriculaData> dataList = new ArrayList<>();
try {
JSONObject mainObj = new JSONObject(response);
JSONArray array = mainObj.getJSONArray("results");
CurriculaData data;
for(int i = 0;i<array.length();i++)
{
data = new CurriculaData();
JSONObject resObj = array.getJSONObject(i);
JSONArray reqArray = resObj.getJSONArray("requirers");
for( int j =0;j<reqArray.length();j++) {
JSONObject reqObj = reqArray.getJSONObject(j);
JSONObject innerObj = reqObj.getJSONObject("learningEvent");
data.setTitle(innerObj.getString("displayName"));
data.setAssignedOn(reqObj.getString("assignedOn"));
}
JSONArray basicDetailArray = resObj.getJSONArray("basicdetail");
for(int k=0;k<basicDetailArray.length();k++) {
JSONObject basicDetailObj = basicDetailArray.getJSONObject(k);
JSONObject statusObj = basicDetailObj.getJSONObject("status");
data.setStatus(statusObj.getString("displayName"));
data.setAcquiredOn(basicDetailObj.getString("acquiredOn"));
JSONObject assignObj = basicDetailObj.getJSONObject("assignee");
data.setAssignedBy(assignObj.getString("displayName"));
}
dataList.add(data);
}
} catch (Exception e) {
e.printStackTrace();
}
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
How to parse HTTP response ton JSON object ?
I changed my json code to:
{
"data": [{
"id": 1,
"sensor1": 76,
"sensor2": 75
}, {
"id": 2,
"sensor1": 76,
"sensor2": 206
}]
}
And my code is now:
JSONObject json = new JSONObject(mJson);
try {
data = json.getJSONArray("data");
for (int i = 0; i < json.length(); i++) {
HashMap<String, Integer> map = new HashMap<String, Integer>();
JSONObject obj = (JSONObject) data.get(i);
map.put(TAG_SENSOR_1, obj.getInt("sensor1"));
map.put(TAG_SENSOR_2, obj.getInt("sensor2"));
dataList.add(data.getInt("id") - 1, map);
}
} catch (JSONException e) {
e.printStackTrace();
}
But I have the same problem
edit your string to this format
{content:[{
first:1,
second:76,
third:75
},
{
first:2,
second:76,
third:75
},
{
first:3,
second:206,
third:75
},
{
first:4,
second:6,
third:175
},
{
first:5,
second:176,
third:75
}]
}
then use JSONObject and JSONArray to convert string
JSONArray array = new JSONObject(string).getJSONArray("content");
for(int i=0;i<array.size();i++){
JSONObject obj = array.get(i);
Log.i(TAG,"obj.getInt = "+obj.getInt("first"));
Log.i(TAG,"obj.getInt = "+obj.getInt("second"));
Log.i(TAG,"obj.getInt = "+obj.getInt("third"));
}