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){
}
Related
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?
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.
How can I parse in Android a Json array of strings and save it in a java string array ( like: xy[ ] ) ?
My Json to be parsed :
[
{
"streets": [ "street1", "street2", "street3",... ],
}
]
Later in my code I want to populated with that array a spinner item in my layout.
Everything i tried enden with only one street item listed in the spinner.
To parse
try {
JSONArray jr = new JSONArray("Your json string");
JSONObject jb = (JSONObject)jr.getJSONObject(0);
JSONArray st = jb.getJSONArray("streets");
for(int i=0;i<st.length();i++)
{
String street = st.getString(i);
Log.i("..........",""+street);
// loop and add it to array or arraylist
}
}catch(Exception e)
{
e.printStackTrace();
}
Once you parse and add it to array. Use the same to populate your spinner.
[ represents json array node
{ represents json object node
Try this..
JSONArray arr = new JSONArray(json string);
for(int i = 0; i < arr.length(); i++){
JSONObject c = arr.getJSONObject(i);
JSONArray ar_in = c.getJSONArray("streets");
for(int j = 0; j < ar_in.length(); j++){
Log.v("result--", ar_in.getString(j));
}
}
We need to make JSON object first. For example,
JSONObject jsonObject = new JSONObject(resp);
// resp is your JSON string
JSONArray arr = jsonObject.getJSONArray("results");
Log.i(LOG, "arr length = " + arr.length());
for(int i=0;i<arr.length();i++)
{...
arr may contains other JSON Objects or JSON array. How to convert the JSON depends on the String. There is a complete example with some explanation about JSON String to JSON array can be found at http://www.hemelix.com/JSONHandling
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;
}
}