Accessing array inside an array - java

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"]

Related

Sorting JSON array by ID

I wrote code that takes a string that holds a JSON data. I'm sorting my JSON object array by ID. When I'm using my method I get this exception: "org.json.JSONException: A JSONArray text must start with '[' at 1 [character 2 line 1]".
What am I missing here and how to solve it?
private static void ResortJsonByUseCaseID( String jsonArrStr )
{
JSONArray jsonArr = new JSONArray(jsonArrStr);
JSONArray sortedJsonArray = new JSONArray();
List<JSONObject> jsonValues = new ArrayList<JSONObject>();
for (int i = 0; i < jsonArr.length(); i++) {
jsonValues.add(jsonArr.getJSONObject(i));
}
java.util.Collections.sort( jsonValues, new java.util.Comparator<JSONObject>() {
private static final String KEY_NAME = "useCaseId";
#Override
public int compare(JSONObject a, JSONObject b) {
String valA = new String();
String valB = new String();
try {
valA = (String) a.get(KEY_NAME);
valB = (String) b.get(KEY_NAME);
}
catch (JSONException e) {
//do something
int tal = 9;
}
return valA.compareTo(valB);
}
});
for (int i = 0; i < jsonArr.length(); i++) {
sortedJsonArray.put(jsonValues.get(i));
}
jsonArrStr = sortedJsonArray.toString();
}
The code you are describing will only work on a json that looks something like this:
[
{ "useCaseId" : "4", ... },
{ "useCaseId" : "1", ... },
{ "useCaseId" : "a", ... },
...
]
As you can see, the string begins with a [ character, like the exception demanded.
Since "most" jsons begin with { I'm guessing that your json structure is different, and then you'll be required to adjust your code accordingly. For example, if your json array is embedded in an object like "most" jsons are:
{
"useCases" : [
{ "useCaseId" : "4", ... },
{ "useCaseId" : "1", ... },
{ "useCaseId" : "a", ... },
...
]
}
then you would have to create a JSONObject obj = new JSONObject(jsonArrStr) and then get the JSONArray by calling (JSONArray)obj.get("useCases").

Generating menu items from JSON file in Android

By reading a JSON file from a local folder, Im trying to generate drawer menu having child items. readJsonDataFromFile(); returns the JSON string. Im using the following code to generate menu.
lstChild = new TreeMap<>();
try {
String jsonDataString = readJsonDataFromFile();
JSONArray menuItemsJsonArray = new JSONArray(jsonDataString);
for (int i = 0; i < menuItemsJsonArray.length(); ++i) {
JSONObject menuItemObject = menuItemsJsonArray.getJSONObject(i);
String catName = menuItemObject.getString("cname");
JSONArray scatJsonArray = new JSONArray(menuItemObject.getString("csubcat"));
for (int j = 0; j < scatJsonArray.length(); ++j) {
JSONObject scatItemObject = scatJsonArray.getJSONObject(j);
//********GENERATING CHILD ITEMS HERE***********
}
lstChild.put(catName,childItem);
}
} catch (IOException | JSONException exception) {
Log.e(HomeActivity.class.getName(), "Unable to parse JSON file.",exception);
}
lstTitle = new ArrayList<>(lstChild.keySet());
I want to generate child items (childItem) and expected record set is like
List<String> childItem = Arrays.asList("Beginner","Intermediate","Advanced","Professional");
JSON string
[
{
"cid": "1",
"cname": "WATCHES",
"cimg": "074321.png",
"csubcat": [
{
"sid": "1",
"sname": "FASTTRACK"
},
{
"sid": "2",
"sname": "TIMEX"
},
{
"sid": "3",
"sname": "ROADSTER"
},
{
"sid": "4",
"sname": "TITAN"
}
]
}
]
Im beginner to Android/Java. Thanks in advance
try {
String jsonDataString = readJsonDataFromFile();
JSONArray menuItemsJsonArray = new JSONArray(jsonDataString);
for (int i = 0; i < menuItemsJsonArray.length(); ++i) {
JSONObject menuItemObject = menuItemsJsonArray.getJSONObject(i);
String catName = menuItemObject.getString("cname");
JSONArray scatJsonArray = new JSONArray(menuItemObject.getString("csubcat"));
List<String> childItem = new ArrayList<>();
for (int j = 0; j < scatJsonArray.length(); ++j) {
JSONObject scatItemObject = scatJsonArray.getJSONObject(j);
childItem.add(scatItemObject. getString("sname"));
}
lstChild.put(catName,childItem);
}
} catch (IOException | JSONException exception) {
Log.e(HomeActivity.class.getName(), "Unable to parse JSON file.",exception);
}

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

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

Array inside JSONArray iteration in java

My Json is:
{
"Response": {
"Asset": [
{
"id": 2461,
"name": "TestAsset7771",
"model_name": "TestModel777",
"serial_number": "TestAsset7771",
"current_data": {
"timestamp": "",
"name": "Temperature",
"value": "?"
}
},
{
"id": 2448,
"model_id": 1229,
"name": "TestAsset777",
"model_name": "TestModel777",
"serial_number": "TestAsset777",
"current_data": {
"timestamp": "",
"name": "Temperature",
"value": "?"
}
}
]
}
}
My code is:
JSONObject outerObject = new JSONObject(jsonObj.toString());
JSONObject innerObject = outerObject.getJSONObject("Response");
JSONArray jsonArray = innerObject.getJSONArray("Asset");
for (int i = 0, size = jsonArray.length(); i < size; i++)
{
JSONObject objectInArray = jsonArray.getJSONObject(i);
String[] elementNames = JSONObject.getNames(objectInArray)
for (String elementName : elementNames)
{
String value = objectInArray.getString(elementName);
System.out.printf("name=%s, value=%s\n", elementName, value);
}
}
For inner array - ie current data, am getting values as:
name=current_data,
value={"timestamp":"","name":"Temperature","value":"?"}
How can i put another inner array so that i can get values of
"timestamp":"", "name":"Temperature", "value":"?" in separate variables instead of complete JSON
Its better to use Gson to parse JSON. Anyway, if you decide to follow as this is, try as :
You have a class like this:
class CurrentData{
String name,timestamp,value;
void print(){
System.out.printf("name=%s, timestamp=%s, value=%s\n", name,timestamp, value);
}
}
Now, change your for loop as follows:
for (String elementName : elementNames)
{
if(!elementName.equals("current_data")){
String value = objectInArray.getString(elementName);
System.out.printf("name=%s, value=%s\n", elementName, value);
}
else{
CurrentData obj=new CurrentData();// You can use array of objects declaring outside the loop as your need
JSONObject curr_object=objectInArray.getJSONObject("current_data");
obj.name=curr_object.getString("name");
obj.timestamp=curr_object.getString("timestamp");
obj.value=curr_object.getString("value");
obj.print();
}
}
for (String elementName : elementNames)
{
JSONObject jsonobject = jsonarray.getJSONObject(elementName);
System.out.printf( "name=%s, value=%s\n",jsonobject.getString("name"),jsonobject.getString("value"));
}
"value" is another jason object, so you can just call "getJasonObject()" to obtain the item and then proceed with that new array as normal.
Edit: I made a fail (not enough C0FFEE in my memory) and corrected thanks to the comment.
JSONObject outerObject = new JSONObject(jsonObj.toString());
JSONObject innerObject = outerObject.getJSONObject("Response");
JSONArray jsonArray = innerObject.getJSONArray("Asset");
for (int i = 0, size = jsonArray.length(); i < size; i++) {
JSONObject objectInArray = jsonArray.getJSONObject(i);
JSONObject currentData = objectInArray.getJSONObject("current_data");
if (currentData != null) {
String timestamp = currentData.getString("timestamp");
String name = currentData.getString("name");
String value = currentData.getString("value");
// Assign above results to array elements or whatever
}
}
//nested jsonarray
FileReader inp=new FileReader("xyz.json");
JSONParser parser=new JSONParser();
Object obj=parser.parse(inp);
JSONArray jsonArray=(JSONArray) obj;
int len=jsonArray.size();
for(i:len)
{
JSONArray json1=(JSONArray) jsonArray.get(i);
Iterato iterator=json1.iterator();
while(iterator.hasNext())
System.out.println(iterator.next());
}

Categories

Resources