JSONObject and JSONArray - Need to get values held in array - java

I have the following JSON data structure:
{
"myRequest": {
"item1": "value1",
"itme2": "value2",
"item3Holder": {
"id": [
"ID001",
"ID002",
"ID003",
"ID004"
]
}
}
}
I need to be able to get the id values from the id [] array.
I can can get the values for item1-3, but can't separate out the id [] array values.
JSONObject requestObj = new JSONObject(data.trim()).getJSONObject("myRequest");
// Retrieve items from JSONObject
String item1 = requestObj.getString("item1");
String item2 = requestObj.getString("item2");
String item3 = requestObj.getString("item3");
// Retrieve all id's
JSONArray ids = requestSubObj.getJSONArray("item3Holder");
for (int i = 0; i < ids.length(); i++) {
String id = ids.toString();
logger.info("id : " + id);
}

I think you should get the objects like this:
JSONObject item3Holder = requestObj.getJSONObject("item3Holder");
JSONArray ids = item3Holder.getJSONArray("id");
Also you need to call .getString(i) for the ids object
for (int i = 0; i < ids.length(); i++) {
String id = ids.getString(i).toString();
logger.info("id : " + id);
}

Related

Fetch value from JSON array based on another value in the array

Here is my JSON response:
[
{
"name":"Canara Atm",
"location_name":"Baker Junction"
},
{
"name":"Canara Atm",
"location_name":"Manarcaud"
},
{
"name":"Canara Atm",
"location_name":"Palai Arunapuram"
},
{
"name":"Canara Atm",
"location_name":"Changanacherry"
}
]
I need to get add values based on a specific location in to to the array, means, for example, location_name":"Baker Junction" is my needed location then to my array I should add only the specified atm name. in the below code all names are being added to the array
try {
JSONArray jsonArray = new JSONArray(response);
JSONObject json = null;
final String xcoords[] = new String[jsonArray.length()];
if (jsonArray.length() != 0) {
for (int i = 0; i < jsonArray.length(); i++) {
json = jsonArray.getJSONObject(i);
xcoords[i] = (json.getString("name"));
}
}
}
this is what i did , you can convert json to list like given below ,
ArrayList<String> list = new ArrayList<>();
for (int i = 0; i < jsonArray.length(); i++) {
json = jsonArray.getJSONObject(i);
Strring s = (json.getString("name"));
list.add(p)
}
then
//you can directly use this value or you can use the index to again fetch the json or for other purpose
int count =0;
int index = 0 ;
for(Sting s : list){
if(s.equals("yourvalue"){
index = count;
}
count++
}
then
if (jsonArray.length() != 0) {
for (int i = 0; i < jsonArray.length(); i++) {
// your index here
json = jsonArray.getJSONObject(index);
xcoords[i] = (json.getString("name"));
}
}

Compare list of JSONArray in ArrayList

I have an ArrayList containing a list of JSONArrays
staffArray = new ArrayList<JSONArray>();
the JSONArray is in a form of this:
[
{
"id": "k40dn-dff02-mm1",
"name": "staff1",
"tel": "0123456789",
},
{
"id": "ch2mq-pmw01-ps6",
"name": "staff2",
"tel": "9876543210",
}
...
]
And the ArrayList will be containing different sizes of JSONArray.
Now I want to check in the ArrayList for each JSONArray, if they contain the same value for "id". So say that if the ArrayList has three different sizes of JSONArray, how can I tell the they each contain a JSONObject with the same value for "id" in it.
So far I have tried this to extract the string:
for(int i = 0; i < staffArray.size(); i++){
JSONArray jsonArray = new JSONArray();
jsonArray = staffArray.get(i);
for(int j = 0; j < jsonArray.length(); j ++){
JSONObject json = null;
try {
json = jsonArray.getJSONObject(j);
String id = json.getString("id");
} catch (JSONException e) {
e.printStackTrace();
}
}
}
If you would like to check for duplicate IDs in your ArrayList, you could do something like this:
ArrayList<JSONArray> staffArray = new ArrayList<>();
Set<String> ids = new HashSet<>();
for (JSONArray array : staffArray) {
for (int i = 0; i < array.length(); i++) {
JSONObject obj = array.getJSONObject(i);
if (!ids.add(obj.getString("id"))) {
// duplicate IDs found, do something
}
}
}
How about using group by to group the json arrays with same id something like this
public static void groupById(List<JSONArray> staffArray) {
Map<String, List<JSONArray>> jsonArraysById = staffArray.stream().collect(Collectors.groupingBy(jsonArray -> getIdFromJsonArray(jsonArray)));
jsonArraysById.forEach((id, arrays) -> {
System.out.println("Arrays with id " + id + " are " + arrays);
});
}
public static String getIdFromJsonArray(JSONArray jsonArray) {
String result = null;
for (int j = 0; j < jsonArray.length(); j++) {
JSONObject json = null;
try {
json = jsonArray.getJSONObject(j);
result = json.getString("id");
} catch (JSONException e) {
e.printStackTrace();
}
}
return result;
}

Java Arrays.asList(columnes).contains() return false

in my application i have columnes variable with some data as :
List<String> columnes = getSingleColumn("id");
now i'm trying to check single string into this array :
Arrays.asList(columnes).contains("1")
this check allways return false
My full code:
List<String> columnes = getSingleColumn("id");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject item = jsonArray.getJSONObject(i);
cList = new Categories();
cList.id = Integer.parseInt(item.getString(SV.FIELD_CATEGORY_ID));
cList.title = item.getString(SV.FIELD_CATEGORY_TITLE);
cList.followers = item.getString(SV.FIELD_CATEGORY_FOLLOWERS);
cList.type = item.getString(SV.FIELD_CATEGORY_TYPE);
cList.date = item.getString(SV.FIELD_CATEGORY_DATE);
cList.imageUrl = item.getString(SV.FIELD_CATEGORY_IMAGE_URL);
Log.e("Check : ", Arrays.asList(columnes).contains(cList.id+""));
} catch (JSONException e) {
}
Arrays.asList(list) returns List<List<String>> not List<String> so contains method can not find your String in that list of list (From #TAsk's answer).Therefore change
Log.e("Check : ", Arrays.asList(columnes).contains(cList.id+""));
to
Log.e("Check : ", columnes.contains(String.valueOf(cList.id)));
and also check value of cList.id as
Log.e("cList id value: ", String.valueOf(cList.id));

How to access JSONArray inside of a JSONArray in a JSON object response

Within this Json response, how do I get access to "smallImageUrls" and get the image url using Java?
Seems like "smallImageUrls" is an array within the "matches" jsonarray. Someone please correct me if I am wrong on that.
{
"attribution":{
"html":"Recipe search powered by <a href='http://www.yummly.com/recipes'><img alt='Yummly' src='http://static.yummly.com/api-logo.png'/></a>",
"url":"http://www.yummly.com/recipes/",
"text":"Recipe search powered by Yummly",
"logo":"http://static.yummly.com/api-logo.png"
},
"totalMatchCount":17663,
"facetCounts":{
},
"matches":[
{
"imageUrlsBySize":{
"90":"http://lh3.ggpht.com/bTkxROvVTjHChEsGLRnkuwPoi-eNrHmESYP3xDHMsIisN-U06z-OfwErSjT5AHvMG0Ccgw8cN4mVqNyjWzbz=s90-c"
},
"sourceDisplayName":"Serious Eats",
"ingredients":[
"mayonnaise",
"crema mexican",
"feta",
"ancho powder",
"garlic",
"coriander leaf",
"shuck corn",
"lime"
],
"id":"Mexican-street-corn-_elotes_-370469",
"smallImageUrls":[
"http://lh5.ggpht.com/itong2VhnBU2mvPtzNimL58MnkC4l113RgNyrEWq8Jf76AsOGOlBoVQyCF-jYDPtzTB-7SoViNzyV5-Xe0NS=s90"
],
"recipeName":"Mexican Street Corn (Elotes)",
"totalTimeInSeconds":2400,
"attributes":{
"cuisine":[
"Mexican"
]
},
"flavors":{
"sweet":0.5,
"sour":0.6666666666666666,
"salty":0.6666666666666666,
"piquant":0.3333333333333333,
"meaty":0.3333333333333333,
"bitter":0.6666666666666666
},
"rating":5
}
],
"criteria":{
"excludedIngredients":null,
"allowedIngredients":null,
"terms":null
}
}
this is the code that I currently have. I can access all the other strings, just not the image urls .
JSONObject resObj = new JSONObject(result);
JSONArray foundrecipes = resObj.getJSONArray("matches");
for(int i = 0;i<foundrecipes.length(); i++){
JSONObject recipe = foundrecipes.getJSONObject(i);
String recipeName = recipe.getString("recipeName");
String rating = recipe.getString("rating");
String id = recipe.getString("id");
String imageurl = recipe.getString("smallImageUrls");
data.add(new Recipes(recipeName, rating, id, imageurl));
}
smallImageUrls, is inside matches that is inside the root, so you have to retrieve matches and, through it, smallImageUrls
JSONObject obj = new JSONObject(...);
JSONArray matches = obj.optJSONArray("matches");
if (matches != null) {
for (int i = 0; i < matchesLenght; i++) {
JSONObject objAtIndex = matches.optJSONObject(i);
if (objAtIndex != null) {
JSONArray smallImageUrls = objAtIndex.optJSONArray("smallImageUrls");
for (int j = 0; j < smallImageUrlsSize; j++) {
String urlAtIndex = smallImageUrls.optString(j);
}
}
}
}

How to store JSONcontaining Nested JSONArray

I'm working on one app in which I have JSON Like..
{
"Group Details":
[
{
"groupMasterId": "25",
"GroupName": "Gangs of Beasts",
"groupIcon": "http://xxx.xxx.xx.x/XYZ/images/evil.png",
"GroupDescription": "Fellowzzzgroup",
"GroupCreatedDate": "2014-04-30 15:41:01",
"GroupMassage": "no such thing is like group msg",
"UserData":
[
{"UserMobile": "1111111111","AdminFlag": "1"},
{"UserMobile": "1234567890","AdminFlag": "0"},
{"UserMobile": "9988776655","AdminFlag": "0"},
{"UserMobile": "234t537535","AdminFlag": "0"},
{"UserMobile": "3489869348","AdminFlag": "0"},
{"UserMobile": "1234567890","AdminFlag": "0"}
]
}
]
}
I want to display Details on simple TextView and UserData in ListView..but the proble in I'm total confused with how to store this data.. I done following code to do it,,but not able to store all UserMobile in single HashMap...
JSONObject jsonObj = new JSONObject(jsonstr);
GroupDetailsArray = jsonObj.getJSONArray(GROUPDETAILS);
HashMap<String, String> groupuser = new HashMap<String, String>();
for (int i = 0; i < GroupDetailsArray.length(); i++) {
JSONObject l = GroupDetailsArray.getJSONObject(i);
// String ID= l.getString(GROUPMASTERID);
String NAME = l.getString(GROUPNAME);
String DESCRIPTION = l.getString(GROUPDESCRIPTION);
String DATE = l.getString(GROUPCREATEDDATE);
String ICON = l.getString(GROUPICON);
JSONArray UsedDataArray = l.getJSONArray(USERDATA);
String ADMIN;
for (int j = 0; j < UsedDataArray.length(); j++) {
JSONObject l1 = UsedDataArray.getJSONObject(j);
if (l1 != null) {
String MOBILENUMBER = l1.getString(USERMOBILE);
if (l1.getString(ADMINFLAG).equals("0")) {
ADMIN = "Member";
} else {
ADMIN = "Admin";
}
// tmp hashmap for single group
groupuser.put(USERMOBILE, MOBILENUMBER);
groupuser.put(ADMINFLAG, ADMIN);
}
}
// tmp hashmap for single group
HashMap<String, String> group = new HashMap<String, String>();
// adding each child node to HashMap key => value
group.put(GROUPNAME, NAME);
group.put(GROUPDESCRIPTION, DESCRIPTION);
group.put(GROUPCREATEDDATE, DATE);
group.put(USERDATA, groupuser.toString());
group.put(GROUPICON, ICON);
// adding group to group list
Utility.groupdetailsarraylist.add(group);
Log.d("groupdetailsarraylist",
Utility.groupdetailsarraylist.toString());
}
please help me to how to store data so that I can use it to store in next Activity...
List list1=new ArrayList<String>();
JSONArray array=jso.getJSONArray("UserData");
for(int i=0;i<array.length();i++)
{ list1.add(array.getJSONObject(i).getString("UserMobile"));
}
Iterator itr=list1.iterator();
while(itr.hasNext())
{
str1=itr.next().e+"\n";
}

Categories

Resources