How to convert JSON array into JSON object - android

I have the following JSON data:
[
{
"sendingReqDataSet": {
"totalCount": 1,
"limit": 50,
"offset": 0,
"status_code": true,
"contacts": [
{
"id": 1,
"request_to": "Shehla_kiran",
"request_by": "ayesha",
"product_name": "Dead Space",
"schedule_date_time": "2016-09-21 00:00:00",
"place": "lhr",
"request_type": "Swap",
"status": "Pending"
},
{
"id": 2,
"request_to": "muqadas",
"request_by": "muqadas",
"product_name": "battleField",
"schedule_date_time": "2016-09-22 00:00:00",
"place": "lhr",
"request_type": "Swap",
"status": "Pending"
},
{
"id": 3,
"request_to": "Shehla_kiran",
"request_by": "Shehla_kiran",
"product_name": "Mario",
"schedule_date_time": "2016-09-12 00:00:00",
"place": "Lahore",
"request_type": "Swap",
"status": "Pending"
},
{
"id": 4,
"request_to": "Shehla_kiran",
"request_by": "Mari",
"product_name": "Mario",
"schedule_date_time": "0000-00-00 00:00:00",
"place": "",
"request_type": "Swap",
"status": "Pending"
},
{
"id": 5,
"request_to": "Shehla_kiran",
"request_by": "Faisal Ali",
"product_name": "Dead Space",
"schedule_date_time": "2016-10-28 00:00:00",
"place": "lahore",
"request_type": "Swap",
"status": "Pending"
},
{
"id": 6,
"request_to": "muqadas",
"request_by": "Faisal Ali",
"product_name": "battleField",
"schedule_date_time": "2016-10-25 00:00:00",
"place": "Canal",
"request_type": "Swap",
"status": "Pending"
},
{
"id": 7,
"request_to": "Shehla_kiran",
"request_by": "Shehla_kiran",
"product_name": "Dead Space",
"schedule_date_time": "2016-10-17 00:00:00",
"place": "Lahore",
"request_type": "Swap",
"status": "Pending"
}
]
}
}
]
I am trying to show it in a list view, but when I try to parse it and show in a list view, it gives me the following error:
W/System.err: org.json.JSONException:
Value [{"sendingReqDataSet":{"totalCount":1,"limit":50,"offset":0,"status_code":true,"contacts":[{"id":1,"request_to":"Shehla_kiran","request_by":"ayesha","product_name":"Dead Space","schedule_date_time":"2016-09-21 00:00:00","place":"lhr","request_type":"Swap","status":"Pending"},{"id":2,"request_to":"muqadas","request_by":"muqadas","product_name":"battleField","schedule_date_time":"2016-09-22 00:00:00","place":"lhr","request_type":"Swap","status":"Pending"},{"id":3,"request_to":"Shehla_kiran","request_by":"Shehla_kiran","product_name":"Mario","schedule_date_time":"2016-09-12 00:00:00","place":"Lahore","request_type":"Swap","status":"Pending"},{"id":4,"request_to":"Shehla_kiran","request_by":"Mari","product_name":"Mario","schedule_date_time":"0000-00-00 00:00:00","place":"","request_type":"Swap","status":"Pending"},{"id":5,"request_to":"Shehla_kiran","request_by":"Faisal Ali","product_name":"Dead Space","schedule_date_time":"2016-10-28 00:00:00","place":"lahore","request_type":"Swap","status":"Pending"},{"id":6,"request_to":"muqadas","request_by":"Faisal Ali","product_name":"battleField","schedule_date_time":"2016-10-25 00:00:00","place":"Canal","request_type":"Swap","status":"Pending"},{"id":7,"request_to":"Shehla_kiran","request_by":"Shehla_kiran","product_name":"Dead Space","schedule_date_time":"2016-10-17 00:00:00","place":"Lahore","request_type":"Swap","status":"Pending"}]}}]
of type org.json.JSONArray cannot be converted to JSONObject
Currently, I am doing this:
try {
// jsonObject = new JSONObject();
JSONObject jsonObject = new JSONObject(json_string);
// JSONArray query = jsonParse.getJSONArray("courses");
jsonArray = jsonObject.getJSONArray("contacts");
int count = 0;
String name, email, moblile;
while (count < jsonArray.length()) {
JSONObject JO = jsonArray.getJSONObject(count);
name = JO.getString("request_to");
email = JO.getString("request_by");
moblile = JO.getString("product_name");
Contacts contacts = new Contacts(name, email, moblile);
contactAdapter.add(contacts);
count++;
}
} catch (JSONException e) {
e.printStackTrace();
}

String data = /*load the json data*/
try {
JSONArray jsonArray = new JSONArray(data);
JSONObject object = jsonArray.getJSONObject(0);
JSONObject sendingReqDataSetObject = object.getJSONObject("sendingReqDataSet");
JSONArray arrayContacts = sendingReqDataSetObject.getJSONArray("contacts");
for (int i = 0; i<arrayContacts.length(); i++) {
JSONObject contactObject = arrayContacts.getJSONObject(i);
System.out.println(contactObject.getString("status"));
}
} catch (JSONException e) {
e.printStackTrace();
}

You can get object by using following code :
jsonArray = jsonObject.getJSONArray("contacts");
for(int i=0; i<jsonArray.size(); i++) {
JSONObject jobject = jsonArray.getJSONObject(i)
}

Use Gson library (https://github.com/google/gson)
Library support converting into JSON or from JSON to object.

JSONArray array = new JSONArray(json_string);
JSONObject obj = array.getObject("sendingReqDataSet");
jsonArray = obj.getJSONArray("contacts");

Related

Why only first Few items are fetched from a JSON Response?

I am trying to parse this URL : http://testproject1.indigierp.com/api/banner_details with POST request. This is the response returned :
{
"msg": true,
"src": [
{
"id": 12,
"banner_name": "https://testproject1.indigierp.com/images/banners/promo1.jpg",
"user_id": "1",
"created_at": "2021-09-22 21:46:04",
"updated_at": "-0001-11-30 00:00:00"
},
{
"id": 14,
"banner_name": "https://testproject1.indigierp.com/images/banners/promo3.jpg",
"user_id": "1",
"created_at": "2021-09-22 21:46:16",
"updated_at": "-0001-11-30 00:00:00"
},
{
"id": 15,
"banner_name": "https://testproject1.indigierp.com/images/banners/promo4.jpg",
"user_id": "1",
"created_at": "2021-09-22 21:46:28",
"updated_at": "-0001-11-30 00:00:00"
},
{
"id": 16,
"banner_name": "https://testproject1.indigierp.com/images/banners/promo4.jpg",
"user_id": "1",
"created_at": "2021-09-23 03:30:41",
"updated_at": "-0001-11-30 00:00:00"
},
{
"id": 17,
"banner_name": "https://testproject1.indigierp.com/images/banners/discountberry.png",
"user_id": "1",
"created_at": "2021-09-23 03:32:37",
"updated_at": "-0001-11-30 00:00:00"
}
]
}
Now, on my Android App only the first 2 data (JSON Object ) is shown. This is my Android code :
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, BANNER_URL, null, response -> {
for (int i = 0; i < response.length(); i++) {
try {
JSONArray jsonArray = response.getJSONArray("src");
JSONObject jsonObject = jsonArray.getJSONObject(i);
Log.e("OBJ Size", String.valueOf(jsonObject.length()));
String bannerName = jsonObject.getString("banner_name");
Log.e("BNAME", bannerName);
sliderModelList.add(new SliderModel(bannerName));
sliderAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
Log.e("JSOnException", e.getLocalizedMessage());
}
I debugged as well. The Log.e OBJ Size returns 5 which is correct , but the next line Log.e("BNAME", bannerName); returns only the first 2 items .
What is wrong here, Please try to help me fix it. Thanks :)
Check with this
for (int i = 0; i < response.length(); i++) {
try {
JSONArray jsonArray = response.getJSONArray("src");
for(int j=0;j<jsonArray.length();j++){
JSONObject jsonObject = jsonArray.getJSONObject(j);
Log.e("OBJ Size", String.valueOf(jsonObject.length()));
String bannerName = jsonObject.getString("banner_name");
Log.e("BNAME", bannerName);
sliderModelList.add(new SliderModel(bannerName));
sliderAdapter.notifyDataSetChanged();
}
} catch (JSONException e) {
e.printStackTrace();
Log.e("JSOnException", e.getLocalizedMessage());
}
response.length() returns "2", because there are 2 fields in the response: "msg" and "src". You're doing the for on a wrong object.
Get the array first, then enumerate it:
JSONArray jsonArray = response.getJSONArray("src");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
...

How to update a specific object inside an array of a JSON file?

format of my json file in internal storage is like,
{
"appointments": [
{
"appointmentId": "app_001",
"appointmentTitle": "Appointment Title1",
"appointmentDate": "2017-11-25",
"appointmentTime": "10:30",
"appointmentStatus": "active",
"appointmentType": "meeting",
"reminder": {
"type": "notification",
"time": "10:15",
"status": "off"
},
"appointmentDescription": "blablablablabla1"
},
{
"appointmentId": "app_002",
"appointmentTitle": "AppointmentTitle2",
"appointmentDate": "2017-11-26",
"appointmentTime": "09:00",
"appointmentStatus": "done",
"appointmentType": "exam",
"reminder": {
"type": "alarm",
"time": "08:45",
"status": "on"
},
"appointmentDescription": "blablablablabla2"
}
]
}
I need to update value of appointmentTitle which has app_001 as appointmentId
my function is,
String configFileString = "";
File configFile = new File(getApplicationContext().getExternalFilesDir("/appointments"), "appointments.json");
try {
configFileString = getStringFromFile(configFile.toString());
JSONObject json = new JSONObject(configFileString);
JSONArray array = json.getJSONArray("appointments");
} catch (Exception e) {
e.printStackTrace();
}
What should be the modifications that I need to do in my code? please help, thanks in advance.
Here you have , you just have to go through the array and update your data:
JSONArray array = json.getJSONArray("appointments");
for(int i=0;i < array.length(); i++){
JSONObject object = array.getJSONObject(i);
String id = object.getString("appointmentId");
if (id.equals("app_001")){
object.put("appointmentTitle","your value updated");
}
}
String stringJSON = array.toString();
//save your data

Android - Getting value from the JSON object

I have this json
{
"results": [
{
"user": {
"gender": "male",
"name": {
"title": "mr",
"first": "herbert",
"last": "davidson"
},
"location": {
"street": "9763 fincher rd",
"city": "melbourne",
"state": "new south wales",
"zip": 26278
},
"email": "herbert.davidson#example.com",
"username": "lazyelephant581",
"password": "abgrtyu",
"salt": "O8ZbSsUL",
"md5": "7575bd959be09bc6d510a6a91750ce40",
"sha1": "0db99de8402e1defbd7935dbd602d99329698d4d",
"sha256": "c283d262115f90b729bb555db3dbecc8d27eebed513d7f01da799dec9e9d3269",
"registered": 1275070071,
"dob": 122409280,
"phone": "05-5742-3228",
"cell": "0481-652-548",
"TFN": "973720989",
"picture": {
"large": "https://randomuser.me/api/portraits/men/24.jpg",
"medium": "https://randomuser.me/api/portraits/med/men/24.jpg",
"thumbnail": "https://randomuser.me/api/portraits/thumb/men/24.jpg"
}
}
}
],
"nationality": "AU",
"seed": "0a69317ece7072e000",
"version": "0.7"
}
and im doing this:(result is the json returned from the service)
try{
JSONObject jsonResponse = new JSONObject(result);
JSONObject jo = jsonResponse.getJSONObject("user");
String nome = jo.getString("username");
}catch(Exception e) {
e.printStackTrace();
}
but gives me this error
org.json.JSONException: No value for username
What im doing wrong? I tryed to do a JSONArray, tryed to get the jsonobject from another jsonobject, but giver an error that cannot convert jsonobject to a jsonarray.
regards!
Rafael
Try this in your code .
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray results = jsonObject.getJSONArray("results");
for (int i = 0; i < results.length(); i++) {
JSONObject jo = results.getJSONObject(i);
JSONObject user = jo.getJSONObject("user");
String username = user.optString("username");
}
} catch (JSONException e) {
e.printStackTrace();
}
Use optString in your code .If your username is null,it will not return error .
The first-level key in your dictionary is "results", not "user". Also, results is an array, so you have to index into that.
You're trying to access: user->username
You need to access: results[0]->user->username

Getting numbered json key values

Below is the response I get from the API.
[{
"claim1": [{
"claim_no": "1",
"claim_date": "14\/06\/2017 12:00:00 AM",
"month_code": "1",
"claim_amount": "8074"
}]
}, {
"billing1": [{
"claim_no": "141",
"month_code": "1",
"miti": "6",
"amount": "7374",
"paid": "7374",
"fee1": "0"
}]
}, {
"claim2": [{
"claim_no": "26",
"claim_date": "20\/06\/2017 12:00:00 AM",
"month_code": "2",
"claim_amount": "2424"
}]
}, {
"billing2": []
}, {
"claim3": [{
"claim_no": "40",
"claim_date": "13\/07\/2017 12:00:00 AM",
"month_code": "3",
"claim_amount": "2924"
}]
}, {
"billing3": [{
"claim_no": "724",
"month_code": "3",
"miti": "13",
"amount": "2924",
"paid": "2924",
"fee1": "0"
}]
}, {
"claim4": [{
"claim_no": "43",
"claim_date": "09\/08\/2017 12:00:00 AM",
"month_code": "4",
"claim_amount": "2424"
}]
}, {
"billing4": [{
"claim_no": "402",
"month_code": "4",
"miti": "20",
"amount": "5348",
"paid": "3124",
"fee1": "0"
}]
}]
I am using the aQuery jsonarray class.
I tried to get it in a JSON object, but got an error like
jsonarray cannot be converted to jsonobject
below is my code.
This code is showing me this error
"org.json.JSONException: No value for claim_no"
I want to get the value of claim_no
aq.ajax("myapiurlhere", JSONArray.class, new AjaxCallback<JSONArray>(){
#Override
public void callback(String url, JSONArray array, AjaxStatus status) {
super.callback(url, array, status);
Log.i("response:", "response:" + url + array);
for (int i = 0; i < array.length(); i++) {
try {
JSONObject object = array.getJSONObject(i);
bill_no = object.getString("claim_no");
Log.i("response:","claim: "+claim_no+" bill: "+object);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
});
I also tried the code below, but I got an error
"claim1 of type org.json.JSONArray cannot be converted to JSONObject"
aq.ajax("myapiurl", JSONArray.class, new AjaxCallback<JSONArray>(){
#Override
public void callback(String url, JSONArray array, AjaxStatus status) {
super.callback(url, array, status);
Log.i("response:", "response:" + url + array);
for (int i = 0; i < array.length(); i++) {
try {
int mycount = i+1;
JSONObject object = array.getJSONObject(i);
JSONObject claimobject = object.getJSONObject("claim"+mycount);
claim_no = claimobject.getString("claim_no");
Log.i("response:","claim: "+claim_no);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
});
This is an array
"claim1": [
You're getting an object
JSONObject claimobject = object.getJSONObject("claim"+mycount);
You need to get an array first
JSONObject claimobject = object.getJSONArray("claim"+mycount).getJSONObject(0);
Also, your API is poorly structured, and int mycount = i+1; will likely fail because you're counting billing and claim elements at the same time
Try this instead
for (int i = 0; i < array.length(); i++) {
int mycount = (i/2)+1;
try {

How to Sort JSON Array from JSON Objects in Android?

I have a JSON array, and I want to sort it Depending on the name and too alphabetically.
My Json is as follows.
[
{
"UserID": 77,
"InvID": 333,
"Email": "sumeetssm#gmail.com",
"Phone": "",
"Name": "Summet",
"Company": "",
"Date": "2014-01-14T00:00:00"
},
{
"UserID": 0,
"InvID": 334,
"Email": "amit#testt.com",
"Phone": "",
"Name": "Amit",
"Company": "",
"Date": "2014-01-14T00:00:00"
},
{
"UserID": 3,
"InvID": 335,
"Email": "amitesh#yahoo.com",
"Phone": "",
"Name": "Amitesh",
"Company": "",
"Date": "2014-01-14T00:00:00"
},
{
"UserID": 0,
"InvID": 336,
"Email": "foobar#test.com",
"Phone": "",
"Name": "FOO",
"Company": "",
"Date": "2014-01-14T00:00:00"
},
{
"UserID": 0,
"InvID": 337,
"Email": "krazy.lance#gmail.com",
"Phone": "",
"Name": "Krazy",
"Company": "",
"Date": "2014-01-14T00:00:00"
},
{
"UserID": 1,
"InvID": 338,
"Email": "test#yahoo.com",
"Phone": "",
"Name": "Test",
"Company": "",
"Date": "2014-01-14T00:00:00"
},
{
"UserID": 0,
"InvID": 339,
"Email": "maktest#yahoo.com",
"Phone": "",
"Name": " ",
"Company": "",
"Date": "2014-01-14T00:00:00"
},
{
"UserID": 0,
"InvID": 340,
"Email": "Sam#rediff.com",
"Phone": "",
"Name": "SAM",
"Company": "",
"Date": "2014-01-14T00:00:00"
},
{
"UserID": 101,
"InvID": 343,
"Email": "anurag#yahoo.com",
"Phone": "",
"Name": "Anurag",
"Company": "",
"Date": "2014-01-14T00:00:00"
},
{
"UserID": 95,
"InvID": 379,
"Email": "s#s.com",
"Phone": "",
"Name": "S",
"Company": "",
"Date": "2014-01-14T00:00:00"
},
{
"UserID": 0,
"InvID": 428,
"Email": "sumeetssm#yahoo.com",
"Phone": "",
"Name": "Summet",
"Company": "",
"Date": "2014-01-16T00:00:00"
},
{
"UserID": 4,
"InvID": 494,
"Email": "sameer#iconnectgroup.com",
"Phone": "",
"Name": "Sameer P",
"Company": "",
"Date": "2014-01-21T00:00:00"
},
{
"UserID": 85,
"InvID": 507,
"Email": "jonny#dep.com",
"Phone": "9404988188",
"Name": "Jonny Dep",
"Company": "Iconnect",
"Date": "2014-01-22T00:00:00"
}
]
As you can see I have a key value "Name" and in that I get respected names. I want to sort this Json array completely based on this names and that too alphabetically.Thanks in advance.
Convert JSONArray to Arraylist<JSONBbject> and use Collections to sort your arraylist
for example :
ArrayList<JSONObject> array = new ArrayList<JSONObject>();
JSONArray jsonArray = new JSONArray();
for (int i = 0; i < jsonArray.length(); i++) {
try {
array.add(jsonArray.getJSONObject(i));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Collections.sort(array, new Comparator<JSONObject>() {
#Override
public int compare(JSONObject lhs, JSONObject rhs) {
// TODO Auto-generated method stub
try {
return (lhs.getString("Name").toLowerCase().compareTo(rhs.getString("Name").toLowerCase()));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return 0;
}
}
});
Firstly, parse the json data and add every json object to List of Object (e.g. Employee)
List<Employee> employees = parseJson(jsonDate);
Collections.sort(employees, new EmployeeComparator());
Here is the comparator implementation:
class EmployeeComparator implements Comparator<Employee> {
#Override
public int compare(Employee o1, Employee o2) {
return o1.getName().compareTo(o2.getName());
}
}
// try this way i have gave demo code you have modify as per your requirement.
public class MyActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try{
JSONArray jsonArray = new JSONArray();
JSONObject jsonObject = new JSONObject();
jsonObject.put("name","Haresh");
JSONObject jsonObject1 = new JSONObject();
jsonObject1.put("name","Akash");
JSONObject jsonObject2 = new JSONObject();
jsonObject2.put("name","Biraj");
JSONObject jsonObject3 = new JSONObject();
jsonObject3.put("name","Salim");
JSONObject jsonObject4 = new JSONObject();
jsonObject4.put("name","Saloni");
jsonArray.put(jsonObject1);
jsonArray.put(jsonObject);
jsonArray.put(jsonObject3);
jsonArray.put(jsonObject2);
jsonArray.put(jsonObject4);
ArrayList<HashMap<String,String>> list = (ArrayList<HashMap<String,String>>)toList(jsonArray);
Collections.sort(list,new Comparator<HashMap<String, String>>() {
#Override
public int compare(HashMap<String, String> stringStringHashMap, HashMap<String, String> stringStringHashMap2) {
return stringStringHashMap.get("name").compareTo(stringStringHashMap2.get("name"));
}
});
for (HashMap<String,String> row : list){
System.out.println("Row :"+row.get("name"));
}
}catch (Exception e){
e.printStackTrace();
}
}
private Object fromJson(Object json) throws JSONException {
if (json == JSONObject.NULL) {
return null;
} else if (json instanceof JSONObject) {
return jsonToMap((JSONObject) json);
} else if (json instanceof JSONArray) {
return toList((JSONArray) json);
} else {
return json;
}
}
public Map<String, String> jsonToMap(JSONObject object) throws JSONException {
Map<String, String> map = new HashMap();
Iterator keys = object.keys();
while (keys.hasNext()) {
String key = (String) keys.next();
map.put(key, fromJson(object.get(key)).toString());
}
return map;
}
#SuppressWarnings({ "rawtypes", "unchecked" })
private List toList(JSONArray array) throws JSONException {
List list = new ArrayList();
int size = array.length();
for (int i = 0; i < size; i++) {
list.add(fromJson(array.get(i)));
}
return list;
}
}
JSONArrays are not sortable. You can extract the data into an ArrayList and then sort with a comparator and then put back into the JSONArray.
On the Android side you generally won't sort objects in JSON format. If they do need to be sorted before you retrieve them, that is something that should occur on the backend.
Alternatively, and this is very common, you will parse the JSON objects into local Java objects (or Collections of objects), and then you can use a comparator to sort the collection based on a certain property that exists within all objects in the collection.
Fortunately both of these tasks have been asked and answered many times before. For more information on parsing JSON see How to parse JSON in Android. For more information on sorting objects in a collection see Android-java- How to sort a list of objects by a certain value within the object.

Categories

Resources