How to store JSONcontaining Nested JSONArray - java

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";
}

Related

Accessing array inside an array

I'm trying to show images array in a list but I didn't figured it out yet, can anyone please help me.
This may seem as a repeated question, but I tried other answers, they didn't work.
My JSON:
[
{
"id": 52,
"name": "viber",
"images": [
"7829-hit-the-vibe.gif",
"8413_Lit.gif",
"8095_Lazergunzoncam.gif",
"7090_LaserCamz.gif",
"2123-vibe-4.gif",
"3175-vibe-3.gif",
"7413-vibe-2.gif",
"1100-vibe.gif",
"6381-lazeroncamz-2.gif"
],
"download": null,
"amount": 9
},
{
"id": 45,
"name": "aesthetic",
"description": "a",
"slug": "6039-aesthetic",
"images": [
"4071_planet.png",
"3499_love_it.png",
"3019_space_bottle.png",
"6033_pixel_flower.png",
"1620-cupcake-pink.gif",
"2760-seashell-pink.gif",
"1794_sparkles.gif",
"2523_RamSip.png"
],
"download": null,
"amount": 8
},
]
My code:
String jsonString = "myjson";
json1 = new Gson().fromJson(jsonString, new TypeToken<ArrayList<HashMap<String, Object>>>(){}.getType());
for(int _repeat24 = 0; _repeat24 < (int)(json1.size()); _repeat24++) {
JSONObject obj = new JSONObject(jsonString);
JSONArray getArray = obj.getJSONArray("images");
JSONObject objects = getArray.getJSONObject(_repeat24);
Iterator key = objects.keys();
while (key.hasNext()) {
String value = key.next();
}
}
My task: I'm trying to save the array images as json in a key value, example:
categoriesMap = new HashMap<>();
categoriesMap.put("name", name);
categoriesMap.put("imagesJson", JSON_I_NEED);
json1.add(categoriesMap);
This should work as a loop for all the array positions.
Thanks.
String response = "YOUR JSON ARRAY FROM API RESPONSE";
try {
JSONArray jsonArray = new JSONArray(response);
List<List<String>> imagesList = new ArrayList<>();
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject obj = jsonArray.getJSONObject(i);
JSONArray imagesArray = obj.getJSONArray("images");
List<String> images = new ArrayList<>();
for (int j = 0; j < imagesArray.length(); j++) {
images.add(imagesArray.getString(j));
}
imagesList.add(images);
}
// Now you have got a list of a list of images
Log.e(TAG, "onCreate: " + imagesList.toString());
} catch (JSONException e) {
e.printStackTrace();
Log.e(TAG, "onCreate: ", e);
}
Use this way to parse your response :
ArrayList<Data> dataList = new ArrayList<Data>();
if(response!=null){
JSONArray mainArray = new JSONArray(response);
for(int i =0; i< mainArray.length();i++){
JSONObject itemObject = mainArray.optJSONObject(i);
Data data = new Data();
data.setName(itemObject.optString("name"));
ArrayList<String> images = new ArrayList<String>();
// parsing images array
String images = itemObject.optJSONArray("images").toString();
// this will set images array for each position : ["a.jpg","b.jpg","c.jpg"]
data.setImages(images);
dataList.add(data);
}
}
Now populate your list adapter with this ArrayList you will be able to access images for each position distinctly
To store images for each position :
Create a Data Class like this :
class Data {
int id ;
String name;
String images;
int amount;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getImages(){
return images;
}
public void setImages(String images){
this.images = images;
}
}
Now to access the images in recycler view adapter :
dataList.get(position).getImages(); // ["a.jpg","b.jpg"]

JSONObject getString returns null on first run

I have this String data = "[ {\"pname\":\"7\", \"qty\":\"222\"}, {\"pname\":\"8\", \"qty\":\"5\"}, {\"pname\":\"10\", \"qty\":\"65\"}, ]" ;
which is on array list, I want to put them on the variable on each loop and save it to the database, but for now I do this code for debugging purpose because at the first loop of the code it is suuposed to output "qty" value but instead it is a null like this {"pname":"7","qty":"222"} null but on the next run of loop it outputs this {"pname":"8","qty":"5"} 222 it seems that on the second loop the first objects qty value is then taken on the second loop, the final output is this
{"pname":"7","qty":"222"} null {"pname":"8","qty":"5"} 222 {"pname":"10","qty":"65"} 5
and this is the code that I have
String data = "[ {\"pname\":\"7\", \"qty\":\"222\"}, {\"pname\":\"8\", \"qty\":\"5\"}, {\"pname\":\"10\", \"qty\":\"65\"}, ]" ;
HashMap<String, String> item = new HashMap<String, String>();
JSONArray jsonArray = new JSONArray(data);
JSONObject jsonObject = new JSONObject();
ArrayList<HashMap> mylist = new ArrayList<HashMap>();
String txtPname = "", txtQty = "";
if (jsonArray == null) {
System.out.println("json is empty");
} else {
for (int i = 0; i < jsonArray.length(); i++) {
jsonObject = jsonArray.getJSONObject(i);
txtPname = item.put("pname", jsonObject.getString("pname"));
txtQty = item.put("qty", jsonObject.getString("qty"));
output.append(jsonObject).append(" ");
output.append(txtQty).append(" ");
}
}
can anyone help me about this? any help will be so much appreciated, Thanks!!!
You are assigning wrong value to txtQty rather than the current value in the JSONObject:
HashMap Put Method (From Docs):
Returns:
the previous value associated with key, or null if there was no
mapping for key. (A null return can also indicate that the map
previously associated null with key.)
Thats why you are getting null at first attempt and 222 at second.
Following code will give you desired result:
String data = "[ {\"pname\":\"7\", \"qty\":\"222\"}, {\"pname\":\"8\", \"qty\":\"5\"}, {\"pname\":\"10\", \"qty\":\"65\"}, ]" ;
HashMap<String, String> item = new HashMap<String, String>();
JSONArray jsonArray = new JSONArray(data);
JSONObject jsonObject = new JSONObject();
ArrayList<HashMap> mylist = new ArrayList<HashMap>();
String txtPname = "", txtQty = "";
if (jsonArray == null) {
System.out.println("json is empty");
} else {
for (int i = 0; i < jsonArray.length(); i++) {
jsonObject = jsonArray.getJSONObject(i);
txtPname = item.put("pname", jsonObject.getString("pname"));
txtQty = item.put("qty", jsonObject.getString("qty"));
output.append(jsonObject).append(" ");
output.append(jsonObject.getString("qty")).append(" ");
}
}

How to get keys in nested json with parent prefix using GSON in java

I have tried the following example.
public static void operate2(JsonElement jsonElement, List keys, JsonElement jsonElement2, String prefix){
String prefixnew = "";
if(jsonElement.isJsonArray()){
JsonArray jsonArray = jsonElement.getAsJsonArray();
for(int i=0; i<jsonArray.size(); i++){
jsonElement = jsonArray.get(i);
operate2(jsonElement, keys, jsonElement2, prefix);
}
}else if(jsonElement.isJsonObject()){
JsonObject jsonObject = jsonElement.getAsJsonObject();
Set<Map.Entry<String,JsonElement>> childEntrySet = jsonObject.entrySet();
for (Map.Entry<String, JsonElement> child: childEntrySet) {
jsonElement2 = child.getValue();
Object keyCheck = new Gson().fromJson(jsonElement2.toString(), Object.class);
if (keyCheck instanceof Map) {
prefix += child.getKey()+"_";
keys.add(prefix);
System.out.println("Map="+child.getKey());
}else if (keyCheck instanceof Collection) {
if(!prefix.equals("")){
prefix += child.getKey()+"_";
keys.add(prefix);
}else{
prefix = child.getKey()+"_";
keys.add(prefix);
}
System.out.println("Collection="+child.getKey());
}else{
prefix += "";
}
operate2(jsonElement2, keys, jsonElement2, prefix);
}
}else{
prefix = "";
}
}
public static void test2(String json){
JsonElement jsonElement = new JsonParser().parse(json);
JsonElement jsonElement2 = null;
String prefix = "";
List keys = new ArrayList();
operate2(jsonElement, keys, jsonElement2, prefix);
Set keySet = new HashSet(keys);
System.out.println("Keys = "+keys);
}
The output I got Keys = [items_, items_contact_, items_contact_records_, items_contact_records_recordings_, items_contact2_]
But I need items_, items_contact_, items_records_ .... As we can see that record is not the child of the contact, so items_contact_records_ should not be there. Instead items_records_ should be.
The source json would be
{
"items": [{
"id": 633706061003,
"fromNumber": "16572307534",
"contact": {
"id": 499354453003,
"homePhone": "16572307534"
},
"records": [{
"id": 353389055003,
"result": "LA",
"recordings": [{
"id": 16427622003
}]
}]
}],
"limit": 100,
"offset": 0,
"totalCount": 5949
}
I would use the following approach:
if the root element is not a json object, return an empty list
otherwise iterate other its entries, and for each one add the key if the value associated with is either an object or an array
proceed recursively for the value
public static List<String> operate(final JsonElement jsonElement, final String prefix, final boolean firstLayer) {
if(jsonElement.isJsonObject() || (!firstLayer && jsonElement.isJsonArray())) {
List<String> keys = new ArrayList<>();
if(jsonElement.isJsonObject()) {
JsonObject jObj = jsonElement.getAsJsonObject();
for(Map.Entry<String, JsonElement> entry : jObj.entrySet()) {
JsonElement value = entry.getValue();
String newPrefix = prefix + entry.getKey();
if(value.isJsonArray() || value.isJsonObject()) {
keys.add(newPrefix);
keys.addAll(operate(value, newPrefix + "_", false));
}
}
} else {
JsonArray array = jsonElement.getAsJsonArray();
for(JsonElement element : array) {
keys.addAll(operate(element, prefix, false));
}
}
return keys;
} else {
return Collections.emptyList();
}
}
and the test method:
public static void test(String json) {
JsonElement jsonElement = new JsonParser().parse(json);
List<String> keys = operate(jsonElement, "", true);
System.out.println("Keys = " + keys);
}
Running it on your example, you'll get:
Keys = [items, items_contact, items_records, items_records_recordings]

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);
}
}
}
}

JSONObject and JSONArray - Need to get values held in array

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);
}

Categories

Resources