Android: JSON Custom Merge - android

I have created two JSON like following,
First Array:
[
{
"id":255,
"is_new":0,
"is_checked":true,
"name":"Towel Rack 650",
"is_favourite":false
},
{
"id":257,
"is_new":0,
"is_checked":true,
"name":"Towel Rod 450",
"is_favourite":false
},
{
"id":259,
"is_new":0,
"is_checked":true,
"name":"Napkin Ring - Round",
"is_favourite":false
}
]
Second Array:
[
{
"id":258,
"is_new":0,
"is_checked":false,
"name":"Towel Rod 650",
"is_favourite":true
},
{
"id":259,
"is_new":0,
"is_checked":false,
"name":"Napkin Ring - Round",
"is_favourite":true
}
]
In that I have to merge both array and also want to keep duplicate values once in final array.
I used following snippet for merging.
private JSONArray concatArray(JSONArray arr1, JSONArray arr2)
throws JSONException {
JSONArray result = new JSONArray();
for (int i = 0; i < arr1.length(); i++) {
result.put(arr1.get(i));
}
for (int i = 0; i < arr2.length(); i++) {
result.put(arr2.get(i));
}
return result;
}
I am getting:
[
{
"id":255,
"is_new":0,
"is_checked":true,
"name":"Towel Rack 650",
"is_favourite":false
},
{
"id":257,
"is_new":0,
"is_checked":true,
"name":"Towel Rod 450",
"is_favourite":false
},
{
"id":259,
"is_new":0,
"is_checked":true,
"name":"Napkin Ring - Round",
"is_favourite":false
},
{
"id":258,
"is_new":0,
"is_checked":false,
"name":"Towel Rod 650",
"is_favourite":true
},
{
"id":259,
"is_new":0,
"is_checked":false,
"name":"Napkin Ring - Round",
"is_favourite":true
}
]
In that I am getting duplicate values of id 259 which has different values of is_checked and is_favourite which I want true value for both like:
{
"id":259,
"is_new":0,
"is_checked":true,
"name":"Napkin Ring - Round",
"is_favourite":true
}
I have also tried SparseArray but not succeed. Is there any way to do this?
Your help would be appreciated.

Alright, I wrote the code for you:
First, preparing the objects:
JSONArray arr1 = new JSONArray(),arr2 = new JSONArray(),result = new JSONArray();
JSONObject jobj = new JSONObject();
try {
jobj.put("id", "255");
jobj.put("is_new", 0);
jobj.put("is_checked", true);
jobj.put("name", "Towel Rack 650");
jobj.put("is_favourite", false);
arr1.put(jobj);
jobj = new JSONObject();
jobj.put("id", "257");
jobj.put("is_new", 0);
jobj.put("is_checked", true);
jobj.put("name", "Towel Rod 450");
jobj.put("is_favourite", false);
arr1.put(jobj);
jobj = new JSONObject();
jobj.put("id", "259");
jobj.put("is_new", 0);
jobj.put("is_checked", true);
jobj.put("name", "Napkin Ring - Round");
jobj.put("is_favourite", false);
arr1.put(jobj);
jobj = new JSONObject();
jobj.put("id", "258");
jobj.put("is_new", 0);
jobj.put("is_checked", false);
jobj.put("name", "Towel Rod 650");
jobj.put("is_favourite", true);
arr2.put(jobj);
jobj = new JSONObject();
jobj.put("id", "259");
jobj.put("is_new", 0);
jobj.put("is_checked", false);
jobj.put("name", "Napkin Ring - Round");
jobj.put("is_favourite", true);
arr2.put(jobj);
result = concatArray(arr1, arr2);
} catch (JSONException e) {
e.printStackTrace();
}
Then, the method:
private JSONArray concatArray(JSONArray arr1, JSONArray arr2)
throws JSONException {
JSONArray result = new JSONArray();
JSONObject jobj1 = new JSONObject(),jobj2 = new JSONObject(),tmpobj = new JSONObject();
Set<String> objectsList = new HashSet<String>();
for (int i = 0; i < arr1.length(); i++) {
if(objectsList.add(arr1.getJSONObject(i).getString("id"))){
result.put(arr1.getJSONObject(i));
}
}
for (int i = 0; i < arr2.length(); i++) {
if(objectsList.add(arr2.getJSONObject(i).getString("id"))){
result.put(arr2.getJSONObject(i));
} else {
jobj1 = arr2.getJSONObject(i);
int index = 0;
for(int j = 0; j < result.length(); j++){
if(result.getJSONObject(j).getString("id").equals(jobj1.getString("id"))){
jobj2 = result.getJSONObject(j);
index = j;
}
}
tmpobj.put("id", jobj2.getString("id"));
tmpobj.put("is_new", jobj2.getInt("is_new"));
if(jobj1.getBoolean("is_checked")||jobj2.getBoolean("is_checked")){
tmpobj.put("is_checked", true);
} else {
tmpobj.put("is_checked", false);
}
tmpobj.put("name", jobj2.getString("name"));
if(jobj1.getBoolean("is_favourite")||jobj2.getBoolean("is_favourite")){
tmpobj.put("is_favourite", true);
} else {
tmpobj.put("is_favourite", false);
}
result.put(index, tmpobj);
}
}
return result;
}

You can add a SparseArray(key:id,value:each JSONObject in your JSONArray) to save your jsonobjects,every get a jsonobject,first check if its id has existed in SparseArray,if not,insert it.or you will do your logic to decide whether to insert it or update it or ignore it.
At last,if you want to get a JSONArray as return type,then add all SparseArray's values to your JSONArray result.

Related

JSONarray separation to lists in android

I have the following JSONarray and I need to have the output like below. Help please.
{
"data": [
{
"Mandal": "Rambilli",
"Village": "Chatametta"
},
{
"Mandal": "Anakapalle",
"Village": "Valluru"
},
{
"Mandal": "Anakapalle",
"Village": "Venkupalem"
},
{
"Mandal": "Rambilli",
"Village": "Chebrolu Konda"
},
{
"Mandal": "Anakapalle",
"Village": "Vetajangalapalem"
},
{
"Mandal": "Anakapalle",
"Village": "Vooderu"
}
]
}
The out put needs to be two lists with names of Mandal
List<String> Rambilli to contain [Chatametta, Chebrolu Konda]
List Anakapalle to contain [Valluru, Venkupalem, Vetajangalapalem, Vooderu]
The major roadblock I'm facing is how to put the name of the mandal to the output list.
I hard coded every thing but Try:
List<String> listOfRambilli = new ArrayList<>();
List<String> listOfAnakapalle = new ArrayList<>();
try {
JSONArray dataArray = jsonData.getJSONArray("data");
for (int i = 0; i < dataArray.length(); i++) {
JSONObject objectInsideDataArray = dataArray.getJSONObject(i);
String village = objectInsideDataArray.getString("Village");
String mandal = objectInsideDataArray.getString("Mandal");
if (mandal.equals("Rambilli"))
listOfRambilli.add(village);
else if (mandal.equals("Anakapalle"))
listOfAnakapalle.add(village);
else
throw new NoSuchElementException();
}
Log.d("TAG", "" + listOfAnakapalle);
Log.d("TAG", "" + listOfRambilli);
} catch (JSONException e) {
e.printStackTrace();
}
Try this way:
JSONArray jsonArray = jsonObject.getJSONArray("data");
ArrayList<String> rambilliList = new ArrayList<>();
ArrayList<String> anakapalleList = new ArrayList<>();
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject listJsonObject = jsonArray.getJSONObject(i);
if(listJsonObject.getString("Mandal").equals("Rambilli")){
rambilliList.add(listJsonObject.getString("Village"));
} else if(listJsonObject.getString("Mandal").equals("Anakapalle")) {
anakapalleList.add(listJsonObject.getString("Village"));
}
}
System.out.println("Rambilli contains" + rambilliList)
System.out.println("Anakapalle contains" + anakapalleList)

How to show value on one textview if their id is same in JSONArray

I have json data that are showing a hotel previous order detail.
I want if date & time are same then "name" of the items should set in same TextView in the ListView with comma(,) separated.
The data I'm getting from API is this:-
{
"error": false,
"checkstatus": [
[
{
"id": "244",
"name": "Chicken Breast Curry",
"date": "2020-02-22 11:13:53"
},
{
"id": "244",
"name": "Vegetarian ",
"date": "2020-02-22 11:13:53"
},
]
[
{
"id": "245",
"name": "Punjabi Royal for 2 person",
"date": "2020-02-25 09:11:23"
},
]
]
}
This is my Java Class:-
for (int i = 0; i < array.length(); i++) {
try {
JSONArray jsonArray = array.getJSONArray(i);
for (int j = 0; j < jsonArray.length(); j++) {
JSONObject object = jsonArray.getJSONObject(j);
sproduct_name = object.getString(TAG_PRODUCT_NAME);
sdate_time = object.getString(TAG_TIME);
orderId = object.getString(TAG_ORDER_ID);
get = new HashMap<>();
get.put(TAG_PRODUCT_NAME, sproduct_name);
get.put(TAG_TIME, sdate_time);
get.put(TAG_ORDER_ID, orderId);
myList.add(get);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
adapter = new SimpleAdapter(getActivity(), myList, R.layout.order_history_child,
new String[]{TAG_PRODUCT_NAME, TAG_TIME, TAG_ORDER_ID},
new int[]{R.id.product_name, R.id.date_time, R.id.order_ids}) {
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final View view = super.getView(position, convertView, parent);
TextView product_name = view.findViewById(R.id.product_name);
TextView date_time = view.findViewById(R.id.date_time);
final TextView orderid = view.findViewById(R.id.order_ids);
return view;
}
};
Now I am getting data like this screenshot:-
This is what I Want:-
Create ArrayList for Date & Time and String Builder
List<String> datetimeList = new ArrayList<String>();
StringBuilder sb = new StringBuilder();
Add the String of Date & Time in your ArrayList and compare with list, if String is already exists or not
for (int j = 0; j < jsonArray.length(); j++) {
JSONObject object = jsonArray.getJSONObject(j);
sdate_time = object.getString(TAG_TIME);
orderId = object.getString(TAG_ORDER_ID);
datetimeList.add(sdate_time);
Scanner input = new Scanner(System.in);
String input = input.next();
boolean isExist = false;
for (String item : datetimeList) {
if (input.equals(datetimeList.get(counter))) {
//Your logic if it's there.
isExist = true;
break;
}
}
if(isExist) {
//Found in the arraylist.
sproduct_name = object.getString(TAG_PRODUCT_NAME);
sb.append(sproduct_name);
get = new HashMap<>();
get.put(TAG_PRODUCT_NAME, sb.toString());
get.put(TAG_TIME, sdate_time);
get.put(TAG_ORDER_ID, orderId);
myList.add(get);
}
else{
sproduct_name = object.getString(TAG_PRODUCT_NAME);
get = new HashMap<>();
get.put(TAG_PRODUCT_NAME, sproduct_name);
get.put(TAG_TIME, sdate_time);
get.put(TAG_ORDER_ID, orderId);
myList.add(get);
}
}
try {
JSONArray jsonArray = array.getJSONArray(i);
for (int j = 0; j < jsonArray.length(); j++) {
JSONObject object = jsonArray.getJSONObject(j);
sproduct_name = object.getString(TAG_PRODUCT_NAME);
sdate_time = object.getString(TAG_TIME);
orderId = object.getString(TAG_ORDER_ID);
get = new HashMap<>();
get.put(TAG_PRODUCT_NAME, sproduct_name);
//check here
if(!object.getString(TAG_TIME).equals(sdate_time)){
get.put(TAG_TIME, sdate_time);
}
get.put(TAG_ORDER_ID, orderId);
myList.add(get)
}

Issue while getting values from json?

Here my json response,
"stops": [
{
"location": "The Sachdevs, 17, GAA 4th Ln, Thousand Lights West, Nungambakkam, Chennai, Tamil Na
"latlong": {
"lon": 80.250285901129,
"lat": 13.05583158449
},
"stop_code": "stop_1522754972",
"status": ""
},
]
error in this line :
jSONObject cat_object2 = latLong_object.getJSONObject(j); Object
cannot appolien in int
Here my java code,
Any one give me the solution.
Object stops = response_object.get("stops");
if (stops instanceof JSONArray) {
JSONArray stops_array = response_object.getJSONArray("stops");
if (stops_array.length() > 0) {
maplist.clear();
for (int k = 0; k < stops_array.length(); k++) {
JSONObject cat_object = stops_array.getJSONObject(k);
MultipleLatLongPojo pojo = new MultipleLatLongPojo();
pojo.setLocation(cat_object.getString("location"));
pojo.setStopcode(cat_object.getString("stop_code"));
pojo.setStatus(cat_object.getString("status"));
JSONObject latLong_object = cat_object.getJSONObject("latlong");
if (latLong_object.length() > 0) {
for (int j = 0; j < latLong_object.length(); j++) {
JSONObject cat_object2 = latLong_object.getJSONObject(j);
MultipleLatLongPojo pojo2 = new MultipleLatLongPojo();
pojo2.setMulti_lat(cat_object2.getString("lon"));
pojo2.setMulti_lon(cat_object2.getString("lat"));
}
} else {
}
}
}
}
Your latlong property in the json is not an array but an object with two properies (lat and lon), so you do not need to iterate through it's length and this part of your code:
JSONObject latLong_object = cat_object.getJSONObject("latlong");
if (latLong_object.length() > 0) {
for (int j = 0; j < latLong_object.length(); j++) {
JSONObject cat_object2 = latLong_object.getJSONObject(j);
MultipleLatLongPojo pojo2 = new MultipleLatLongPojo();
pojo2.setMulti_lat(cat_object2.getString("lon"));
pojo2.setMulti_lon(cat_object2.getString("lat"));
}
}
should be something like this:
JSONObject latLong_object = cat_object.getJSONObject("latlong");
if(latLong_object != null) {
MultipleLatLongPojo pojo2 = new MultipleLatLongPojo();
pojo2.setMulti_lat(latLong_object.getString("lon"));
pojo2.setMulti_lon(latLong_object.getString("lat"));
}

Parsing JSON for android the JSON is valid but cant get anything back

I'm having trouble getting the String "lf" in this case North Atlantic Treaty Organization
[
{
"sf": "NATO",
"lfs": [
{
"lf": "North Atlantic Treaty Organization",
"freq": 13,
"since": 2001,
"vars": [
{
"lf": "North Atlantic Treaty Organization",
"freq": 13,
"since": 2001
}
]
}
]
}
]
//MY CODE
try {
JSONObject jsonObject = new JSONObject(result);
JSONArray jsonArray = jsonObject.getJSONArray(ITEM_TAG);
for(int i = 0; i < jsonArray.length(); i++) {
JSONObject c = jsonArray.getJSONObject(i);
String name = c.getString("lf");
acronyms = new ArrayList<>();
acronyms.add(name);
}
} catch (Exception e) {
}
try {
JSONArray jsonArray1 = new JSONArray(JsonString);
for (int i = 0; i <= jsonArray1.length(); i++) {
JSONObject jsonObject2 = jsonArray1.getJSONObject(i);
String mStrSf = jsonObject2.getString("sf");
Toast.makeText(getApplicationContext(),mStrSf.toString(), Toast.LENGTH_LONG).show();
JSONArray jsonArray3 = jsonObject2.getJSONArray("lfs");
for (int j = 0; j <= jsonArray3.length(); j++) {
JSONObject jsonObject4 = jsonArray3.getJSONObject(j);
String mStrIf = jsonObject4.getString("lf");
String mStrFreq = jsonObject4.getString("freq");
String mStrSince = jsonObject4.getString("since");
Toast.makeText(getApplicationContext(),mStrIf+"\n"+mStrFreq+"\n"+mStrSince, Toast.LENGTH_LONG).show();
JSONArray jsonArray5 = jsonObject4.getJSONArray("vars");
for (int k = 0; k <= jsonArray5.length(); k++) {
JSONObject jsonObject6 = jsonArray5.getJSONObject(k);
String mStrIf1 = jsonObject6.getString("lf");
String mStrFreq1 = jsonObject6.getString("freq");
String mStrSince1 = jsonObject6.getString("since");
Toast.makeText(getApplicationContext(),mStrIf1+"\n"+mStrFreq1+"\n"+mStrSince1, Toast.LENGTH_LONG).show();
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
You are interpreting the json in a wrong way... if you analyse the json chain you will get this:
as you can see you have an array inside and array...
hope the picture helps you to see it better.
You have to again loop through the jsonArray to get "lf" key value.
Try this...
try {
JSONObject jsonObject = new JSONObject(result);
JSONArray jsonArray = jsonObject.getJSONArray(ITEM_TAG);
for(int i = 0; i < jsonArray.length(); i++) {
JSONObject c = jsonArray.getJSONObject(i);
JSONArray array = c.getJSONArray("lfs");
for(int j=0;j<array.length();j++){
JSONObject obj = array.getJSONObject(j);
String name = obj.getString("lf");
}
}
} catch (Exception e) {
}

how I can access data from a JSONArray in Android?

how I can access data from a JSONArray? It is this and contains this information:
"deadlines": [
{
"start": 1439539200,
"end": 1439542800
},
{
"start": 1440144000,
"end": 1440147600
},
{
"start": 0,
"end": 0
}
]
I need to have in a String tag each item "start". Thanks
EDIT
My code is this:
JSONArray array = moduleObject.specialForcedConf;
// array = [{"deadlines":[{"start":1439539200,"end":1439542800},{"start":1440144000,"end":1440147600},{"start":0,"end":0}]}]
for (int j=0; j < array.length(); j++)
{
try
{
JSONObject obj = array.getJSONObject(j);
String start = obj.getString("start");
String end = obj.getString("end");
Log.e("", "start = " + start);
}
catch (JSONException e)
{
Log.e("", "error = " + e.getMessage());
}
}
I get this error:
"error = No value for start"
Do this
JSONArray array = moduleObject.specialForcedConf;
// array = [{"deadlines":[{"start":1439539200,"end":1439542800},{"start":1440144000,"end":1440147600},{"start":0,"end":0}]}]
JSONArray jArray = array.getJSONObject(0).getJSONArray("deadlines");
for (int i = 0; i < jArray.length(); i++) // assuming your array is jArray
{
try
{
JSONObject obj = jArray.getJSONObject(i);
String start= obj.getString("start"); // store in an ArrayList
String end = obj.getString("end"); //// store in an ArrayList
}
catch (JSONException e)
{
// Error
}
}
JSONArray mJsonArray=new JSONArray("Deadlines");
for(int i=0;i<mJsonArray.length();i++){
JSONObject mJsonObject=new JSONObject(mJsonArray.get(i).toString));
String start = mJsonObject.optString("start","");
String end = mJsonObject.optString("end","");
}
Try this:
StringBuilder sb = new StringBuilder();
JSONArray arr = new JSONArray("deadlines");
for(int i=0;i<arr.length;i++){
JSONObject obj = arr.getJSONObject(i);
sb.append(obj.get("start").toString());
sb.append(",");
}
String strStartTag = sb;
JSONArray ja = new JSONArray(yourjsondata));
for (int i = 0; i < ja.length(); i++) {
JSONObject jo_feed = new JSONObject(ja.get(i).toString());
String start = jo_feed.getString("start");
}

Categories

Resources