I'm parsing a JSON string in Android which looks like this:
[
{
"id":70,
"selection":"25"
},
{
"id":71,
"selection":"50"
},
{
"id":72,
"selection":"50"
}
]
Now I want to get the total count of all selection and display it inside a textview. Can anyone give me an example how to do this, or any tutorial about this?
For example:
selection 25 = 1
selection 50 = 2
Thanks for any help!
I think what you're looking for is something like this:
JsonArray selections = new JsonArray(); // This is your parsed json object
HashMap<Integer, Integer> count = new HashMap<>();
for (JsonElement element : selections) {
JsonObject jsonObject = element.getAsJsonObject();
if(jsonObject.has("selection")) {
int selValue = jsonObject.get("selection").getAsInt();
if(count.containsKey(selValue)) {
count.put(selValue, count.get(selValue) + 1);
} else {
count.put(selValue, 1);
}
}
}
What this will do is loop over your json array and get the value of each selection element. To keep track of the count it increments the count inside of the count hashmap.
You can then get the count for a specific value from the hashmap:
count.get(25); // returns 1
count.get(50); // returns 2
// etc...
If you are using Jackson in Java 8, you can first convert the given JSON string to List<Map<String, Object>>, then transform it into List<Integer> for selection. Finally, you can count occurrences in this list as follows:
ObjectMapper mapper = new ObjectMapper();
List<Map<String, Object>> jsonObj = mapper.readValue(jsonStr, new TypeReference<List<Map<String, Object>>>(){});
Map<Integer, Long> counted = jsonObj.stream()
.map(x -> Integer.valueOf(x.get("selection").toString()))
.collect(Collectors.toList())
.stream()
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
System.out.println(counted.toString());
Console output:
{50=2, 25=1}
ArrayList<String> data = new ArrayList<>();
ArrayList<String> datacount = new ArrayList<>();
jsonStr = "Your JSON"
JSONArray jsonArr= null;
try {
jsonArr = new JSONArray(jsonStr);
for (int i = 0; i < jsonArr.length(); i++) {
JSONObject jsonObj = jsonArr.getJSONObject(i);
//here you can set to TextView
String selection = jsonObj.getString("selection");
//System.out.println("adcac"+selection);
if (data.contains(selection)) {
int index = data.indexOf(selection);
int count = Integer.parseInt(datacount.get(index))+1;
// System.out.println("Index==="+index+"---count---"+count);
datacount.set(index,String.valueOf(count));
} else {
datacount.add(String.valueOf(1));
data.add(selection);
}
// Here you can get data and data count...
// System.out.println("data---"+datacount.toString());
}
} catch (JSONException e) {
e.printStackTrace();
}
you can get the array of the json and iterate and calculate the sum of the selection
JSONArray selections = jsonObj.getJSONArray("selections");
// looping through All Selections
int totalCount = selections.length();
Why doesn't anybody use Json Path to solve this in two lines?
Related
I am struggling with a specific problem, that I cannot think of correctly. The following is the problem
I have a map with key value like the following, i just used strings here
String key = "activate.message.success"
String value = "success"
String key1 = "activate.title"
String value1 = "Good Title"
String key2 = "activate.message.error"
String value2 = "error"
String key3 = "activate.message.short.poll"
String value3 = "This is short poll"
I need to build a json like the following
{
"activate":{
"message":{
"success":"success",
"error":"error",
"short":{
"poll":"This is short poll"
}
},
"title":"Good Title"
}
}
I could not think of a proper solution for this use case and struggling for 3 hours. I thought of using recursion, but i dont how exactly i could do. Please help with this. I am using java for this, I should use generic JSONObject to solve as there is not POJO mappings. So far I have just splitted the strings using separtor and stored in an another map like the following
public Map<String, Object> getJsonObjectFromKeyValueMap(Map<String, String> stringValueMap,
Map<String, Object> stringObjectMap) {
for (Entry entry : stringValueMap.entrySet()) {
String[] keyValueArrayString = entry.getKey().toString().split("\\.");
int sizeOfMap = keyValueArrayString.length;
int i = 0;
String concatString = "";
for (String processKey : keyValueArrayString) {
if (i < sizeOfMap - 1) {
concatString += processKey + ".";
stringObjectMap.put(concatString, (Object) new JSONObject());
} else {
concatString += processKey;
stringObjectMap.put(concatString, entry.getValue());
concatString = "";
}
i++;
}
}
return stringObjectMap;
}
First, let's update your data into a proper map :
Map<String, String> data = new HashMap<>();
data.put("activate.message.success", "success");
data.put("activate.title", "Good Title");
data.put("activate.message.error", "error");
data.put("activate.message.short.poll", "This is short poll");
Then, your logic is pretty close, for each node but the last, you create a new JSONObject, for the last, you insert the value.
If you try to build a JSONObject instead of the map directly, you would get a pretty good result already, well somewhat of a result.
The following will iterate a Map<String, String> of data.
For each entry, we split the key to getting the nodes.
Then, we just need to move in the json, if a node doesn't exist, we create it.
Then, for the last value, create the value.
public static JSONObject build(Map<String, String> data) {
JSONObject json = new JSONObject();
//Iterate the map entries
for (Entry<String, String> e : data.entrySet()) {
String[] keys = e.getKey().split("\\.");
// start from the root
JSONObject current = json;
for (int i = 0; i < keys.length; ++i) {
String key = keys[i];
//Search for the current node
try {
//If it exist, do nothing
current = current.getJSONObject(key);
} //If it does not exist
catch (JSONException ex) {
//Is it the last node, create the value
if (i == keys.length - 1) {
current.put(key, e.getValue());
} //Not the last node, create a new JSONObject
else {
JSONObject tmp = new JSONObject();
current.put(key, tmp);
current = tmp; //Always replace current with the last node to go deeped each iteration
}
}
}
}
return json;
}
And the example :
public static void main(String[] args) {
Map<String, String> data = new HashMap<>();
data.put("activate.message.success", "success");
data.put("activate.title", "Good Title");
data.put("activate.message.error", "error");
data.put("activate.message.short.poll", "This is short poll");
JSONObject json = build(data);
System.out.println(json.toString(4));
}
Ouptut:
{"activate": {
"message": {
"success": "success",
"short": {"poll": "This is short poll"},
"error": "error"
},
"title": "Good Title"
}}
Note : I used an exception to check for the existance of the key, if the map is huge, this could have some impact so you can simply use :
if(current.isNull(key)){
if (i == keys.length - 1) {
current.put(key, e.getValue());
} else {
JSONObject tmp = new JSONObject();
current.put(key, tmp);
current = tmp;
}
} else {
current = current.getJSONObject(key);
}
This was created using org.json/json
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.
Am comparing javascript array of elements with other elements within the same array. If elements are same means, I have to give the same number for all the common elements. If the elements are different I have to give some different number for all the nonidentical elements in another element.
for example :
Array structure = [{Location, Date, Number}]
array = [{ 'LA','2017-12-01',1},
{ 'LA','2017-12-01',1},
{ 'NY','2017-12-01',2},
{ 'NY','2016-10-01',3},
{ 'LA','2017-12-01',1},
{ 'LA','2017-12-01',1},
{ 'LA','2017-12-01',1}]
In this array 'Number' is dynamic element, It should be populate on the following rules.
`key1 = location + '-' +date;`
Consider Key1 is the first element ( combination of location + date ). If the same key1 is present in the array, then 'Number' is common for all the same Key1.
In the above example {'LA','2017-12-01',1 } having the same number 1.
{ 'NY','2017-12-01',2} having the number 2. and { 'NY','2016-10-01',3}, having the number 3 because eventhough location is common but date is different.
Please find my code below that am trying. But it giving same number for all the array elements.
JSONObject orderObj=database.getOrder(salesorderId);
JSONArray lineArr = orderObj.getJSONArray("order_items"); //lines
JSONObject lineObj = null;
for(int i=0;i<lineArr.length();i++)
{
lineObj = lineArr.getJSONObject(i);
String source_location=lineObj.getString("source_location");
String key=source_location.concat(lineObj.has("ship_date") ?
lineObj.getString("ship_date") : lineObj.getString("req_ship_date"));
Map map=new HashMap();
if(!map.containsKey(key)){
map.put(key, map.size()+1);
}
lineObj.put("number", map.get(key).toString());
}
orderObj.append("order_items", lineObj);
Move the instantiating of map out of the for loop:
JSONObject orderObj = database.getOrder(salesorderId);
JSONArray lineArr = orderObj.getJSONArray("order_items"); //lines
JSONObject lineObj = null;
// To here:
Map map = new HashMap();
for ( int i = 0; i < lineArr.length(); ++i )
{
lineObj = lineArr.getJSONObject(i);
String source_location = lineObj.getString("source_location");
String key = source_location.concat( lineObj.has("ship_date") ?
lineObj.getString("ship_date") : lineObj.getString("req_ship_date"));
// From here: Map map=new HashMap();
if ( !map.containsKey(key) )
{
map.put(key, map.size() + 1);
}
lineObj.put("number", map.get(key).toString());
}
orderObj.append("order_items", lineObj);
Given the following JSON
{
"Users":[
{
"Username":"John",
"Password":"Doe"
},
{
"Username":"Anna",
"Password":"Smith"
},
{
"Username":"Peter",
"Password":"Jones"
}
]
}
I am trying to extract an array list of UserName & Password
JSONObject jobj = new JSONObject(jsonData);
JSONArray userArray = jobj.getJSONArray("Users"); // Now I got the Array of Users
I need to do something to extract all the user and password. What function is there for this? I am using the org JSON library
for (int i=0;i<userArray.length();i++)
{
// something like that
usernameList = userArray[i].getData("Username");
passwordList = userArray[i].getData("Password");
}
Just try with:
usernameList = userArray.getJSONObject(i).getString("Username");
to get a List of all userNames and Password you need to iterate through all the elements in the array and then add individual userNames and passwords to the lists.
Something Like this:
List<String> userList = new ArrayList<>();
List<String> passwordList = new ArrayList<>();
try {
for (int i = 0; i < userArray.length(); i++) {
JSONObject user = userArray.getJSONObject(i);
userList.add(user.getString("Username"));
passwordList.add(user.getString("Password"));
}
}catch(Exception e){
}
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;
}
}