Array inside JSONArray iteration in java - 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());
}

Related

How can i go through this json in java?

I am working on an Android project, in which I am using Volley to consume an Api. The query is being done correctly and the next JSON returns to me. I am trying to access the elements of this jsonArray in java
[
{
"Estado": 1,
"_id": "5dfd27fb971f730f31cc12d5",
"empresas": "5dfbeec1f87e0e3030b38143",
"Codigo": "1001AZXL001",
"Codigo_Barras": "7702345654127",
"Descripcion": "JEAN talla XL ",
"Detalles": [
{
"_id": "5dfd27fb971f730f31cc12d7",
"bodegas": "5dfd2383971f730f31cc12cf",
"Cantidad": 6,
"Precio": 150000,
"Unidad_Medida": "UND"
},
{
"_id": "5dfd27fb971f730f31cc12d6",
"bodegas": "5dfd23b7971f730f31cc12d0",
"Cantidad": 15,
"Precio": 150000,
"Unidad_Medida": "UND"
}
],
"Talla": "XL",
"Color": "AZ",
"Minimo": 5000,
"Maximo": 30000,
"Fecha_Creacion": "2019-12-20T19:58:51.720Z"
}
]
For that I am using the following code
public void onResponse(JSONArray jsonArray) {
for(int i = 0; i < jsonArray.length(); i++) {
try {
JSONObject jsonObject = jsonArray.getJSONObject(i);
descripcionProducto = jsonObject.getString("Descripcion");
tallaProducto = jsonObject.getString("Talla");
txtDescripcion.setText(descripcionProducto);
txtUnidades.setText(tallaProducto);
}
catch(JSONException e) {
}
}
}
But I cannot access the elements that are inside the "Detalles" object
Use the following :
public void onResponse(JSONArray jsonArray) {
for(int i = 0; i < jsonArray.length(); i++) {
try {
JSONObject jsonObject = jsonArray.getJSONObject(i);
descripcionProducto = jsonObject.getString("Descripcion");
tallaProducto = jsonObject.getString("Talla");
txtDescripcion.setText(descripcionProducto);
txtUnidades.setText(tallaProducto);
JSONArray array = jsonObject.getJSONArray("Detalles")
for(int j = 0; j < array.length() ; ++j){
try{
JSONObject jsonObject2 = array.getJSONObject(j);
//ACCESS THE PARAMETERS OF detalles HERE FOR EX :
String bodegas = jsonObject2.getString("bodegas");
}catch(JSONException e) {}
}
}
catch(JSONException e) {
}
}
}
This is another Jsonarray, if you want to get the data inside, you Need to get the Jsonarray and read the data from there.
JSONArray array = jsonObject.getJSONArray("Detalles")
If you want the Data inside this Array you can Access them as you already did

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").

How to get some elements in nested JSON objects in a JSON array

I hava this JSON:
[
{
"title": "This a Sample title for each post_title",
"excerpt": "And this is a sample of the post_body,
"author": "King Spark",
"featured_picture": {
"source": "https://exapmple.com/blah/blah/image.jpg",
"year": "2015",
"ownwer": "Akim Man",
},
},...
From the json I only need the title, excerpt elements of the main objects. Then from the featured_picture objects, I want only the source element.
I have written this code and it seems not to be working:
private void parseData(JSONArray array){
Log.d(TAG, "Parsing array");
for(int i = 0; i<array.length(); i++) {
PostItems postItem = new PostItems();
JSONObject jsonObject = null;
try {
jsonObject = array.getJSONObject(i);
postItem.setPost_title(jsonObject.getString(ConfigPost.TAG_POST_TITLE));
postItem.setPost_body(jsonObject.getString(ConfigPost.TAG_POST_BODY));
//Parsing featured_pocture object
for (int f = 0; f<array.length(); f++) {
JSONObject object = array.getJSONObject(f);
JSONObject postImage = object.getJSONObject("featured_picture");
String imageURL = postImage.getString("source");
postItem.setPost_image(imageURL);
}
} catch (JSONException w) {
w.printStackTrace();
//Toast.makeText(this, "Error in parsing Json", Toast.LENGTH_LONG).show();
}
mPostItemsList.add(postItem);
}
}
Try to parse the nested JSON like this way:
private void parseData(JSONArray array){
Log.d(TAG, "Parsing array");
for(int i = 0; i<array.length(); i++) {
PostItems postItem = new PostItems();
JSONObject jsonObject = null;
try {
jsonObject = array.getJSONObject(i);
postItem.setPost_title(jsonObject.getString(ConfigPost.TAG_POST_TITLE));
postItem.setPost_body(jsonObject.getString(ConfigPost.TAG_POST_BODY));
//Parsing featured_picture object
JSONObject postImage = jsonObject.getJSONObject("featured_picture");
postItem.setPost_image(postImage.getString("source"));
} catch (JSONException w) {
w.printStackTrace();
//Toast.makeText(this, "Error in parsing Json", Toast.LENGTH_LONG).show();
}
mPostItemsList.add(postItem);
}
}
You won't continue read the array here
for (int f = 0; f<array.length(); f++) {
featured_picture is an entry in the map and returns a map too.
The acces should be like this :
array.getJSONObject(i).getJSONObject("featured_picture").getString("source");
You have to identify object and array in json then find value by key, once you learnt then complexity of json doesn't matter to parse follow tutorial
your code for (int f = 0; f<array.length(); f++) {
JSONObject object = array.getJSONObject(f);
JSONObject postImage = object.getJSONObject("featured_picture");
String imageURL = postImage.getString("source");
postItem.setPost_image(imageURL);
}
is not correct, this part of json is not an array but an object inside another jsonObject.
Here no need to iterate loop to read nested JSONobject.
Because "featured_picture" gives only JSONObject not an array. In case if its return array you should read like this:
JSONObject rootObject=new JSONObject();
JSONArray nestedObject=rootObject.getJSONArray("key");
Here i modified your code in correct manner hope will it help for you.
for(int i = 0; i<array.length(); i++) {
PostItems postItem = new PostItems();
JSONObject jsonObject = null;
try {
jsonObject = array.getJSONObject(i);
postItem.setPost_title(jsonObject.getString(ConfigPost.TAG_POST_TITLE));
postItem.setPost_body(jsonObject.getString(ConfigPost.TAG_POST_BODY));
//Parsing featured_pocture object
JSONObject postImage = jsonObject.getJSONObject("featured_picture");
String imageURL = postImage.getString("source");
postItem.setPost_image(imageURL);
} catch (JSONException w) {
w.printStackTrace();
//Toast.makeText(this, "Error in parsing Json", Toast.LENGTH_LONG).show();
}

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

Categories

Resources