I have a json data, And I want to sort it in java. For every category that is not existing, I want to create a new List. after that or if the category exists, I want to add the data "desc" "title" "link1" and "link2" to it.
if (jsonStr != null) try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JSONArray products = jsonObj.getJSONArray("Products");
// looping through All products
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
String category = c.getString("category");
String title = c.getString("title");
String desc = c.getString("desc");
String link1 = c.getString("link1");
String link2 = c.getString("link2");
// tmp hash map for single contact
// HashMap<String, String> contact = new HashMap<>();
List<String> Product = new ArrayList<>();
// adding each child node to HashMap key => value
Product.add(category);
Product.add(title);
Product.add(desc);
Product.add(link1);
Product.add(link2);
if (!categories.contains(category)) {
List<List<String>> [category] = new ArrayList<>(); //here I want to create the name of the new list dynamically if it's not existing yet
}
[category].add(Product);
// adding contact to contact list
categories.add([category]); // and finally adding the category to the categories list ( List<List<List<String>>>)
}
You need to add your new category ArrayList to your categories and keep a reference on it. You can use the handy method of get() from the Map to hit two flies with one stone e.g. something like this
List<List<String>> yourCategoryList = null;
if((yourCategoryList = categories.get(category)) == null){
yourCategoryList = new ArrayList<>();
categories.put(category, yourCategoryList );
}
yourCategoryList.add(product);
Related
I have a list of objects and am converting into JSONArray. Am iterating over the JSONObjects and making an array of JSONObjects.
Now, i want to avoid duplicates objects to get insert into the JSONArray.
Please find my java code below.
JSONArray responseArray1 = new JSONArray();
if (!itemList.isEmpty())
{
jsonArray = new JSONArray(itemList);
for (int i = 0; i < jsonArray.length(); i++)
{
JSONObject jsonObj = jsonArray.getJSONObject(i);
JSONObject responseObj = new JSONObject();
String attr_label = jsonObj.optString("attr_label");
if(StringUtils.equalsIgnoreCase(attr_label, "long_description")) {
long_description = jsonObj.optString("value");
}
else if(StringUtils.equalsIgnoreCase(attr_label, "description")) {
description = jsonObj.optString("value");
}
responseObj.put("id", jsonObj.opt("id")); // i will get duplicate id
responseObj.put("code", jsonObj.opt("code")); // i will get duplicate code
responseObj.put("long_description", long_description);
responseObj.put("description", description);
responseArray1.put(responseObj);
}
}
Please find my actual jsonArray :
[
{
"code":"xyaz",
"attr_label":"long_description",
"id":"12717",
"value":"Command Module"
},
{
"code":"xyaz",
"attr_label":"description",
"id":"12717",
"value":"Set Point Adjustment"
},
]
Am expecting like the below jsonArray :
[
{
"code":"xyaz",
"id":"12717",
"long_description":"Command Module"
"description" : "Set Point Adjustment"
}
]
Update :
I have tried with the below code to avoid duplicate insertion of id & code field. but is not working properly. Its inserting duplicates also.
List<String> dummyList=new ArrayList<String>();
JSONArray responseArray2 = new JSONArray(itemList);
if (!itemList.isEmpty())
{
jsonArray = new JSONArray(itemList);
for (int i = 0; i < jsonArray.length(); i++)
{
JSONObject jsonObj = jsonArray.getJSONObject(i);
JSONObject responseObj = new JSONObject();
String itemCode = jsonObj.optString("code");
String id = jsonObj.optString("id");
if(!dummyList.contains(itemCode) && !dummyList.contains(id) ) {
dummyList.add(String.valueOf(jsonObj.opt("id")));
dummyList.add(String.valueOf(jsonObj.opt("code")));
responseObj.put("id", jsonObj.opt("id"));
responseObj.put("code", jsonObj.opt("code"));
responseObj.put("long_description", long_description);
responseObj.put("description", description);
responseArray2.put(responseObj);
}
}
}
Make a temporary array list and add unique code in that arrayList and check if it already exists in arrayList then don't put this again
String code = jsonObj.opt("code");
if(!arrayList.contains(code))
{
arrayList.add(code);
responseObj.put("id", jsonObj.opt("id"));
responseObj.put("code", jsonObj.opt("code"));
responseObj.put("long_description", long_description);
responseObj.put("description", description);
}
use TreeSet and add Comparator to their constructor in which it compare the duplicate data of the object.
for example:-
Set<Sample> sampleSet=new TreeSet<>(new Sample());
where Sample Class look like:-
class Sample implements Camparator<Sample>{
private String name;
private String id;
//getter
//setter
#Override
public String compare(Sample o1,Sample o2){
return o1.getName.compareTo(o2.getName);
}
}
This will give a set of unique name entries.
I am trying to add Objects from MySQL database on ArrayList Object but result gives me only one row
i am using custom adapter on my ListView, i think i could use loop multiple objects to ArrayList object but i failed , please help me,
my code :
String driver_fullname = json.getString("driver_fullname");
String driver_phonenumber = json.getString("driver_phonenumber");
String plate_no = json.getString("plate_no");
String parking_name = json.getString("parking_name");
List<PaymentTiming_Items> getAllDiverDetails = new ArrayList<PaymentTiming_Items>();
PaymentTiming_Items timingItems = new PaymentTiming_Items();
timingItems.setPlateNo(plate_no);
timingItems.setParkingName(parking_name);
timingItems.setDriverFullName(driver_fullname);
getAllDiverDetails.add(timingItems); // store all drivers' info to
}
if (getAllDiverDetails.size() !=0) {
userList = new ArrayList<> (getAllDiverDetails);
listAdapter = new PaymentTiming_ListAdapter(getApplicationContext(), userList);
myList.setAdapter(listAdapter);
}
Looks like you are creating an ArrayList everytime you parse an object. If I understand correctly, your code should be something like that:
// ArrayList will be created only once for a json response.
List<PaymentTiming_Items> getAllDiverDetails = new ArrayList<PaymentTiming_Items>();
//Now parse add all elements in json response and add to list.
for(all items in your jsonResponse List ) {
//Parse fields from json object
String driver_fullname = json.getString("driver_fullname");
String driver_phonenumber = json.getString("driver_phonenumber");
String plate_no = json.getString("plate_no");
String parking_name = json.getString("parking_name");
//create object
PaymentTiming_Items timingItems = new PaymentTiming_Items();
timingItems.setPlateNo(plate_no);
timingItems.setParkingName(parking_name);
timingItems.setDriverFullName(driver_fullname);
getAllDiverDetails.add(timingItems); // store all drivers' info to
}
//Now list will have all the items, Add this list to adapter.
if (getAllDiverDetails.size() !=0) {
userList = new ArrayList<>(getAllDiverDetails);
listAdapter = new PaymentTiming_ListAdapter(getApplicationContext(), userList);
myList.setAdapter(listAdapter);
}
Suppose Your Server gives a result in JSONArray say response as a String Try the following
List<PaymentTiming_Items> getAllDiverDetails = new ArrayList<PaymentTiming_Items>();
JSONArray jsonArray = new JSONArray(response);
int size = jsonArray.length();
if (size > 0)
{
for (int i = 0; i < size; i++)
{
JSONObject jsonObject = jsonArray.getJSONObject(i);
String driver_fullname = json.getString("driver_fullname");
String driver_phonenumber = json.getString("driver_phonenumber");
String plate_no = json.getString("plate_no");
String parking_name = json.getString("parking_name");
PaymentTiming_Items timingItems = new PaymentTiming_Items();
timingItems.setPlateNo(plate_no);
timingItems.setParkingName(parking_name);
timingItems.setDriverFullName(driver_fullname);
getAllDiverDetails.add(timingItems); // store all drivers' info to
}
}
if (getAllDiverDetails.size() !=0) {
userList = new ArrayList<> (getAllDiverDetails);
listAdapter = new PaymentTiming_ListAdapter(getApplicationContext(), userList);
myList.setAdapter(listAdapter);
}
You must use JSONArray for getting list of items from JSON. And then populate your ArrayList with them and pass to your adapter.
I'm trying to get data from json. I can get data at first state.
But how to get data "ascending" and "descending" and show it on another activity in listview ?
Here's My Json
[{"category_name":"Food","filter_type":"Sort by","field_name":"","type":"VALUE","table_name":"","item_list":["Ascending","Descending"]}
And here's my Java code
if (jsonStr != null) {
try {
foods = new JSONArray(jsonStr);
// looping through All Contacts
for (int i = 0; i < foods.length(); i++) {
JSONObject c = foods.getJSONObject(i);
if(c.getString("category_name").equals("Food")) {
String category_name = c.getString(TAG_CATEGORY_NAME);
String table_name = c.getString(TAG_TABLE_NAME);
String item_list = c.getString(TAG_ITEM_LIST);
// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
contact.put(TAG_CATEGORY_NAME, category_name);
contact.put(TAG_TABLE_NAME, table_name);
contact.put(TAG_ITEM_LIST, item_list);
// adding contact to contact list
foodlistfilter.add(contact);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
I'm trying to follow this tutorial http://www.androidhive.info/2012/01/android-json-parsing-tutorial/, but i still don't fully understand.
Let me explain this.
[ means its an array.
{ is an object.
In your case it's an array whcih contains an -JSONObject with name category_name, filter_type and field_name. type and table_name and a new jsonarray with object item_list.
How can you parse this string?
Here is an example:
String str = "[{"category_name":"Food","filter_type":"Sort by","field_name":"","type":"VALUE","table_name":"","item_list":["Ascending","Descending"]}";
JSONArray jsonArray = new JSONArray(str);
//now it holds the JSONObject.
for (int i = 0; i<= jsonArray.length(); i++) {
//now we loop through and get the jsonObject
JSONObject jsonObj = new JSONObject(jsonArray.getJsonObject(i));
//now it contains your data.
Log.d("Category_nameValue=", jsonObj.getString("category_name"));
//now we want to get the array from the item_list.
JSONArray itemList = new JSONArray(jsonObj.getString("item_list"));
//now itemList.getString(1); === Ascending while itemList.getString(2) == Descending
//now itemList contains several new objects which can also be looped as the parent one.
}
Since you now know how to create an JSONArray, you can start sorting it.
This has been answered already at Android how to sort JSONArray of JSONObjects
If you want to send those data to another Activity you can use the JSONArray.toString() method and send it via Intents.
This is easy explained at Pass a String from one Activity to another Activity in Android
Hope this helps.
If you're new, I would recommend you think about using Gson to parse your Json response directly to a java entity class. So you will avoid to manually parse all your responses.
Your JSON response
[{"category_name":"Food","filter_type":"Sort by","field_name":"","type":"VALUE","table_name":"","item_list":["Ascending","Descending"]}
The entity representing the response
public class MyEntity {
String category_name;
String filter_type;
String field_name;
String type;
String table_name;
String [] item_list;
// getters / setters ...
}
Parsing the response
Gson gson = new Gson();
MyEntity myEntity = gson.fromJson(response, MyEntity.class);
Finally, to send the data, start the new Activity with extras
Intent intent = new Intent(this, AnotherActivity.class);
intent.putExtra("EXTRA_DATA", myEntity.getCategoryName());
startActivity(intent);
Now you recover the extra data on your AnotherActivity
Intent intent = getIntent();
String categoryName = intent.getStringExtra("EXTRA_DATA");
And you can fill the ListView using an ArrayAdapter: Example
To get a JSONArray from your JSONObject c
simply write:
JSONArray itemList = c.getJSONArray(name);
then you can iterate through that data like any other array
for (int i = 0; i < itemList.length(); i++) {
// do something
}
This is an android app that gets data from two different JSON URLs. Then I want to mix their data and put them in a map. To do so, I use a nested for loop. But the problem is it only show YEARS and SYSTEMDATA2 and not SYSTEMDATA1. I think my nested loop is not correct.
Does anyone know the reason?
for(int i = 0; i < array2System1.length(); i++){
c1 = array2System1.getJSONObject(i);
for(int x = 0; x < array2System2.length(); x++){
c2 = array2System2.getJSONObject(x);
}
//Storing JSON item in a Variable
valueSystem2 = c2.getString(SYSTEMDATA2);
year = c1.getString(YEAR);
valueSystem1 = c1.getString(SYSTEMDATA1);
// Adding value HashMap key => value
HashMap<String, String> map = new HashMap<String, String>();
map.put(SYSTEMDATA1, valueSystem1);
map.put(SYSTEMDATA2, valueSystem2);
map.put(YEAR, year);
mylist.add(map);
list=(ListView)findViewById(R.id.list);
ListAdapter adapter = new SimpleAdapter(Search.this, mylist,
R.layout.list_M,
new String[] {SYSTEMDATA1, SYSTEMDATA2, YEAR}, new int[] {
R.id.systemData1, R.id.systemData2, R.id.years});
mylist.setAdapter(adapter);
}
result should be like
Year value(SYSTEMDATA2) value(SYSTEMDATA1)
Current problem
it does not show one of the values. (SYSTEMDATA1 or SYSTEMDATA2)
http://i40.tinypic.com/2wqykvr.png
NEW UPDATE
//Getting JSON Array
JSONObject myJson1 = jsons[0];
JSONObject myJson2 = jsons[1];
try {
List<Map<String, String>> listValues = new ArrayList<Map<String, String>>();
JSONArray array1C1 = myJson1.getJSONArray("myDATA");
JSONArray array2C1 = array1C1.getJSONArray(1);
JSONArray array1C2 = myJson2.getJSONArray("myDATA");
JSONArray array2C2 = array1C2.getJSONArray(1);
for (int i=0; i<array2C1.length(); i++)
{
JSONObject entryJsonC1 = array2C1.getJSONObject(i);
String val1 = entryJsonC1.getString(SYSTEMDATA1);
String year = entryJsonC1.getString("date");
JSONObject entryJsonC2 = array2C2.getJSONObject(i);
String val2 = entryJsonC2.getString(SYSTEMDATA2);
Map<String, String> map = new HashMap<String, String>();
map.put(SYSTEMDATA1, val1);
map.put(SYSTEMDATA2, val2);
map.put(YEAR, year);
listValues.add(map);
}
list = (ListView) findViewById(R.id.list);
String[] adaptersKeys = new String[] {SYSTEMDATA1, SYSTEMDATA2, YEAR};
int[] adapterViews = new int[] {R.id.systemData1, R.id.systemData2, R.id.years};
ListAdapter adapter = new SimpleAdapter(MultiMainActivity.this, listValues, R.layout.list2, adaptersKeys, adapterViews);
list.setAdapter(adapter);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Now the result is like: YEAR SAME-VALUE SAME-VALUE
for(int i=0; i<array2System1.length(); i++)
{
c1 = array2System1.getJSONObject(i);
year = c1.getString(YEAR);
valueSystem1 = c1.getString(SYSTEMDATA1);
for(int x=0; x<array2System2.length(); x++)
{
c2 = array2System2.getJSONObject(x);
//Storing JSON item in a Variable
valueSystem2 = c2.getString(SYSTEMDATA2);
// Adding value HashMap key => value
HashMap<String, String> map = new HashMap<String, String>();
map.put(SYSTEMDATA1, valueSystem1);
map.put(SYSTEMDATA2, valueSystem2);
map.put(YEAR, year);
mylist.add(map);
}
}
list = (ListView)findViewById(R.id.list);
ListAdapter adapter = new SimpleAdapter(Search.this, mylist, R.layout.list_M, new String[] {SYSTEMDATA1, SYSTEMDATA2, YEAR}, new int[] {R.id.systemData1, R.id.systemData2, R.id.years});
// Shoudl be list and not mylist
list.setAdapter(adapter);
You need to put all your code in the inner loop. Currently you just close the inner loop - it runs and overwrites c2 and does nothing.
Something like:
for(int i = 0; i < array2System1.length(); i++){
c1 = array2System1.getJSONObject(i);
for(int x = 0; x < array2System2.length(); x++){
c2 = array2System2.getJSONObject(x);
//Storing JSON item in a Variable
valueSystem2 = c2.getString(SYSTEMDATA2);
year = c1.getString(YEAR);
valueSystem1 = c1.getString(SYSTEMDATA1);
// Adding value HashMap key => value
HashMap<String, String> map = new HashMap<String, String>();
map.put(SYSTEMDATA1, valueSystem1);
map.put(SYSTEMDATA2, valueSystem2);
map.put(YEAR, year);
mylist.add(map);
}
}
The second for loop closes very early. it should be as follows.
for(int x = 0; x < array2System2.length(); x++){
c2 = array2System2.getJSONObject(x);
//Storing JSON item in a Variable
valueSystem2 = c2.getString(SYSTEMDATA2);
year = c1.getString(YEAR);
valueSystem1 = c1.getString(SYSTEMDATA1);
// Adding value HashMap key => value
HashMap<String, String> map = new HashMap<String, String>();
map.put(SYSTEMDATA1, valueSystem1);
map.put(SYSTEMDATA2, valueSystem2);
map.put(YEAR, year);
mylist.add(map);
} // This is where it should get closed
Otherwise, you are just reassigning the c2 variable and loosing the other values execpt the last value. Now, you will be able to place the valueSystem1, valueSystem2 and YEAR values in map and then added to the list. Hope this helps
List<Map<String, String>> listValues = new ArrayList<Map<String, String>>();
JSONArray jsonArray = new JSONArray(.....); // Contains all the indicators
for (int i=0; i<jsonArray.length(); i++)
{
JSONObject entryJson = jsonArray.getJsonObject(i);
// Check integrity
if (!entryJson.hasKey("country")) throw new Exception("No 'country' key found");
if (!entryJson.hasKey("value")) throw new Exception("No 'value' key found");
if (!entryJson.hasKey("date")) throw new Exception("No 'date' key found");
// Get country
JSONObject countryJson = entryJson.getJsonObject("country");
if (!countryJson.hasKey("value")) throw new Exception("No 'value' key found");
String country = countryJson.getString("value");
// Get population
String population = entryJson.getString("value");
// Get year
String year = entryJson.getString("date");
// Create a new Map
Map<String, String> map = new HashMap<String, String>();
map.put(SYSTEMDATA1, country);
map.put(SYSTEMDATA2, population);
map.put(YEAR, year);
// Add to list
listValues.add(map);
}
// Get the ListView
ListView Llist = (ListView) findViewById(R.id.list);
// Create a new adapter to attach this listView
String[] adapterKeys = new String[] {SYSTEMDATA1, SYSTEMDATA2, YEAR};
int[] adapterViews = new int[] {R.id.systemData1, R.id.systemData2, R.id.years};
ListAdapter adapter = new SimpleAdapter(Search.this, listValues, R.layout.list_M, adapterKeys, adapterViews);
// Attach the adapter to the listView
Llist.setAdapter(adapter);
Here is another way that should work better. I haven't tested the code as it was made in notepad. Please tell me if you have any issue.
Because you have defined this:
private static final String SYSTEMDATA1 = "value";
private static final String SYSTEMDATA2 = "value";
//you can't have 2 entries with the same key
private static final String SYSTEMDATA2_KEY = "value2";
The issue appears where you are creating your map:
// Adding value HashMap key => value
HashMap<String, String> map = new HashMap<String, String>();
map.put(SYSTEMDATA1, valueSystem1);
map.put(SYSTEMDATA2_KEY, valueSystem2);
map.put(YEAR, year);
A Map is:
An object that maps keys to values. A map cannot contain duplicate keys; each key can map to at most one value
From the docs for put() method:
Associates the specified value with the specified key in this map (optional operation). If the map previously contained a mapping for the key, the old value is replaced by the specified value.
So you place valueSystem1 using SYSTEMDATA1 as key, which is "value" and then you place valueSystem2 using SYSTEMDATA2 as key, which is ALSO "value", so you are overwriting valueSystem1!
See the edit below...
EDIT:
I'm guessing that to retrieve your values, you must use keys which are "value", that's fine, but to insert in the map later, you must have unique keys. If you still have SYSTEMDATA1="value" and SYSTEMDATA2="value", add one more which you'll use to store in the map and later in the adapter:
//you can't have 2 entries with the same key
private static final String SYSTEMDATA2_KEY = "value2";
// Create a new Map
Map<String, String> map = new HashMap<String, String>();
map.put(SYSTEMDATA1, val1);
map.put(SYSTEMDATA2_KEY, val2);
map.put(YEAR, year);
and then, when you set your adapter keys:
// Create a new adapter to attach this listView
String[] adapterKeys = new String[] {SYSTEMDATA1, SYSTEMDATA2_KEY, YEAR};
Code updated in my original answer.
I have a JSON string like this of data for a table in an android app. one of {} is a row of data for the table. I want to separate these {}s into an array and then each element inside this array into other sub-arrays separating other elements inside {}. Please suggest an appropriate way of accomplishing this criteria using JSON. Thank you.
[
{
"nodeName":"prime_mtsc22#smpp3",
"nodeId":"MTSC3",
"tidPrefix":"4",
"optStatus":"offline",
"daStart":"1",
"daEnd":"3",
"description":"Description"
},
{
"nodeName":"prime_mtsc22#smpp2",
"nodeId":"MTSC58",
"tidPrefix":"1",
"optStatus":"blocked",
"daStart":"5",
"daEnd":"10",
"description":"new description"
},
{
"nodeName":"prime_mtsc22#smpp1",
"nodeId":"MTSC1",
"tidPrefix":"15",
"optStatus":"online",
"daStart":"12",
"daEnd":"20",
"description":"Description"
},
{
"nodeName":"prime_mtsc22#smpp0",
"nodeId":"MTSC15",
"tidPrefix":"15",
"optStatus":"offline",
"daStart":"25",
"daEnd":"30",
"description":"Description"
}
]
ok so in that case the code to use is this
String jsonString = <your jsonString>;
// THIS IS NOT NEEDED ANYMORE
//JSONObject json = new JSONObject(jsonString);
JSONArray topArray = null;
try {
// Getting your top array
// THIS IS NOT NEEDED ANYMORE
//topArray = json.getJSONArray(jsonString);
//use this instead
topArray = new JSONArray(jsonString);
// looping through All elements
for(int i = 0; i < topArray.length(); i++){
JSONObject c = topArray.getJSONObject(i);
//list holding row data
List<NodePOJO> nodeList = new ArrayList<NodePOJO>();
// Storing each json item in variable
String nodeName = c.getString("nodeName");
String nodeID = c.getString("nodeID");
NodePOJO pojo = new NodePOJO();
pojo.setNodeName(nodeName);
//add rest of the json data to NodePOJO class
//the object to list
nodeList.add(pojo);
}
} catch (JSONException e) {
e.printStackTrace();
}
ok?
Use JSONObject for this http://developer.android.com/reference/org/json/JSONObject.html
Example
String jsonString = <your jsonString>;
JSONObject json = new JSONObject(jsonString);
JSONObject topArray = ;
try {
// Getting your top array
topArray = json.getJSONArray(TAG_ARRAY_TOP);
// looping through All elements
for(int i = 0; i < topArray.length(); i++){
JSONObject c = topArray.getJSONObject(i);
//list holding row data
List<NodePOJO> nodeList = new ArrayList<NodePOJO>();
// Storing each json item in variable
String nodeName = c.getString("nodeName");
String nodeID = c.getString("nodeID");
NodePOJO pojo = new NodePOJO();
pojo.setNodeName(nodeName);
//add rest of the json data to NodePOJO class
//the object to list
nodeList.add(pojo);
}
} catch (JSONException e) {
e.printStackTrace();
}
Use the NodePOJO class to hold each row values.
public class NodePOJO {
private String nodeName;
// do for rest of the json row data
public void setNodeName(String nodeName) {
this.nodeName = nodeName;
}
public String getNodeName() {
return this.nodeName;
}
}