How to Get JSON Array Within JSON Object? - java

This is my JSON:
{
"data": [
{
"id": 1,
"Name": "Choc Cake",
"Image": "1.jpg",
"Category": "Meal",
"Method": "",
"Ingredients": [
{
"name": "1 Cup Ice"
},
{
"name": "1 Bag Beans"
}
]
},
{
"id": 2,
"Name": "Ice Cake",
"Image": "dfdsfdsfsdfdfdsf.jpg",
"Category": "Meal",
"Method": "",
"Ingredients": [
{
"name": "1 Cup Ice"
}
]
}
]
}
And this is how I am getting the id and name, you can see this part works fine in returning JSON values that are not array values.
//getting whole json string
JSONObject jsonObj = new JSONObject(jsonStr);
//extracting data array from json string
JSONArray ja_data = jsonObj.getJSONArray("data");
int length = jsonObj .length();
//loop to get all json objects from data json array
for(int i=0; i<length; i++)
{
JSONObject jObj = ja_data.getJSONObject(i);
Toast.makeText(this, jObj.getString("Name"), Toast.LENGTH_LONG).show();
// getting inner array Ingredients
JSONArray ja = jObj.getJSONArray("Ingredients");
int len = ja.length();
}
Now i'm trying to get the values from the ingredients array and I am not sure how to get them? This is what I have been trying thus far.
//getting whole json string
JSONObject jsonObj = new JSONObject(jsonStr);
//extracting data array from json string
JSONArray ja_data = jsonObj.getJSONArray("data");
int length = jsonObj .length();
//loop to get all json objects from data json array
for(int i=0; i<length; i++)
{
JSONObject jObj = ja_data.getJSONObject(i);
Toast.makeText(this, jObj.getString("Name"), Toast.LENGTH_LONG).show();
// getting inner array Ingredients
JSONArray ja = jObj.getJSONArray("Ingredients");
int len = ja.length();
// getting json objects from Ingredients json array
for(int j=0; j<len; j++)
{
JSONObject json = ja.getJSONObject(j);
Toast.makeText(this, json.getString("name"), Toast.LENGTH_LONG).show();
}
}
But doing it this way is not working, how can I get it to work?

Solved, use array list of string to get name from Ingredients. Use below code:
JSONObject jsonObj = new JSONObject(jsonStr);
//extracting data array from json string
JSONArray ja_data = jsonObj.getJSONArray("data");
int length = ja_data.length();
//loop to get all json objects from data json array
for(int i=0; i<length; i++){
JSONObject jObj = ja_data.getJSONObject(i);
Toast.makeText(this, jObj.getString("Name"), Toast.LENGTH_LONG).show();
// getting inner array Ingredients
JSONArray ja = jObj.getJSONArray("Ingredients");
int len = ja.length();
ArrayList<String> Ingredients_names = new ArrayList<>();
for(int j=0; j<len; j++){
JSONObject json = ja.getJSONObject(j);
Ingredients_names.add(json.getString("name"));
}
}

JSONObject jsonObject =new JSONObject(jsonStr);
JSONArray jsonArray = jsonObject.getJSONArray("data");
for(int i=0;i<jsonArray.length;i++){
JSONObject json = jsonArray.getJSONObject(i);
String id = json.getString("id");
String name=json.getString("name");
JSONArray ingArray = json.getJSONArray("Ingredients") // here you are going to get ingredients
for(int j=0;j<ingArray.length;j++){
JSONObject ingredObject= ingArray.getJSONObject(j);
String ingName = ingredObject.getString("name");//so you are going to get ingredient name
Log.e("name",ingName); // you will get
}
}

JSONObject jsonObj = new JSONObject(jsonString);
JSONArray jArray = jsonObj.getJSONArray("data");
int length = jArray.length();
for(int i=0; i<length; i++)
{
JSONObject jObj = jArray.getJSONObject(i);
String id = jObj.optString("id");
String name=jObj.optString("name");
JSONArray ingredientArray = jObj.getJSONArray("Ingredients");
int size = ingredientArray.length();
ArrayList<String> Ingredients = new ArrayList<>();
for(int j=0; j<size; j++)
{
JSONObject json = ja.getJSONObject(j);
Ingredients.add(json.optString("name"));
}
}

Your int length = jsonObj.length(); should be int length = ja_data.length();

Gson gson = new Gson();
Type listType = new TypeToken<List<Data>>() {}.getType();
List<Data> cartProductList = gson.fromJson(response.body().get("data"), listType);
Toast.makeText(getContext(), ""+cartProductList.get(0).getCity(), Toast.LENGTH_SHORT).show();

Related

How to Get String From Parse JSON without String Id in Android Studio

How do I get a string from Parse JSON with data like below?
My Data JSON :
[
[
"John Gorman",
"3344764667200003",
"Student",
"2018-08-09 08:21:30.807"
],
[
"Andy William",
"3403032311690003",
"Student",
"2018-08-09 08:21:30.807"
],
[
"Thomas Endry",
"3408932311690078",
"Student",
"2018-08-09 08:21:30.807"
],
[
"Robet Calm",
"3403077711690890",
"Student",
"2018-08-09 08:21:30.807"
]
]
I use the code below, then to get the string what I have to do, I really don't understand, if there is help, I really need to thank you.
try {
JSONObject object = new JSONObject(result);
JSONArray jsonArray = object.getJSONArray("");
//JSONArray jsonArray = new JSONArray(result);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject c = jsonArray.getJSONObject(i);
String name = c.getString("What should I write here");
System.out.println(c.getString(""));
}
I want to get the string from Parse JSON that I have
How do I get a string for listview, for example:
John Gorman
3344764667200003
Student
Andy William
3403032311690003
Student
Thomas Endry
3408932311690078
Student
Robet Calm
3403077711690890
Student
A couple of things are wrong with the posted code. See my comments inline:
JSONObject object = new JSONObject(result);
^^^^^^^^^^^^^^^^^^^^^^
the content of result is not an object, but an array!
JSONArray jsonArray = object.getJSONArray("");
^^
a proper JSON document had better not have empty keys!
//JSONArray jsonArray = new JSONArray(result);
^^^^^^^^^^^^^^^^^^^^^
this was actually going in the right direction!
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject c = jsonArray.getJSONObject(i);
^^^^^^^^^^^^^^^^^^^^^^^^^^
the i-th element of the array is not an object, but an array!
Fixing the issues above:
JSONArray jsonArray = new JSONArray(result);
for (int i = 0; i < jsonArray.length(); i++) {
JSONArray subArray = jsonArray.getJSONArray(i);
for (int j = 0; j < subArray.length(); j++) {
System.out.println(subArray.getString(j));
}
System.out.println();
}
You are receiving a JSONArray not object so use the below code.
for(int i=0;i<jsonarray.length();i++){
JSONArray array=jsonarray.getJSONArray(i);
for(int j=0;j<array.length();j++){
Log.d(TAG,array.getString(j));
}
}
You can do something like this:
try {
JSONObject object = new JSONObject(result);
JSONArray jsonArray = object.getJSONArray("");
//JSONArray jsonArray = new JSONArray(result);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject c = jsonArray.getJSONObject(i);
String name = c.getString(0);
String id = c.getString(1);
String student = c.getString(2);
// and so on ... This index refers to the index number on the string inside json object
System.out.println(name);
}
Hope this answers your query.
Following method will construct a list of string from the given Json. You can pass that list in the adapter of the list view.
public List<String> getList (String result) throws JSONException {
List<String> list = new LinkedList<>();
JSONArray jsonArray = new JSONArray(result);
for (int i = 0; i < jsonArray.length(); i++) {
JSONArray arr = jsonArray.getJSONArray(i);
StringBuilder sb = new StringBuilder();
for(int j=0;j<arr.length(); j++) {
sb.append(arr.getString(j));
if(j<arr.length()-1) sb.append("\n");
}
list.add(sb.toString());
}
return list;
}

How to get data json from array of the year in array android studio?

I have problem when I try to get data from a JSON array in Android Studio.
I want to get data from year 2015, 2016 and 2018 populate them in different textviews.
This is my JSON:
"data": [
{
"id": "7",
"kecamatan": "Blambangan Umpu",
"year": {
"2015": {
"id": "27",
"value": "60200"
},
"2016": {
"id": "41",
"value": "61516"
},
"2018": {
"id": "7",
"value": ""
}
},
"avg": 2.14
},
and this is my mainactivity
try {
JSONObject jsonObject = new JSONObject(s);
JSONArray array = jsonObject.getJSONArray("data");
// JSONArray array = new JSONArray(s);
for (int i = 0; i < array.length(); i ++) {
JSONObject o = array.getJSONObject(i);
String id = o.getString("id");
String kec = o.getString("kecamatan");
String avg = o.getString("avg");
String tahun = o.getString("year");
// JSONArray array2 = o.getJSONArray("year");
// for (int j = 0; j<array2.length(); j++) {
// JSONObject p = array2.getJSONObject(j);
// String value = p.getString("value");
ListItem item = new ListItem(id, kec, avg, tahun, avg);
listItems.add(item);
// }
}
adapter = new MyAdapter(listItems, getApplicationContext());
recyclerView.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
year is a JSONObject with 2015,2016 and 2018 as keys and JSONObject as values, So get year JSONObject and then get keys and values by iterating it
for (int i = 0 ; i<array.length(); i++) {
JSONObject o = array.getJSONObject(i);
String id = o.getString("id");
String kec = o.getString("kecamatan");
String avg = o.getString("avg");
JSONObject yearObject = o.JSONObject("year"); //get JSONObject
Iterator<String> itr = yearObject.keys();
while(itr.hasNext()) {
String year = itr.next();
JSONObject obj = o.get("year"); //2015
System.out.println(obj.getString("id")); //27
System.out.println(obj.getString("value")); //60200
}
//Add required fields into `ListItem`
ListItem item = new ListItem(id,kec,avg,tahun,avg);
listItems.add(item);
}

How can I parse array of json objects using GSON into JAVA two-dimensional array?

I Have such kind of JSON string:
[{
"id": 3,
"city": "Ilmenau",
"floor": null,
"housenumber": "35",
"streetname": "Blumenstraße",
"zip": "98693"
}, {
"id": 4,
"city": "Berlin",
"floor": null,
"housenumber": "54",
"streetname": "Bogdansplatz",
"zip": "194354"
}]
And I need it to be parsed into two-dimensional array that will look like this:
enter image description here
How can I make it, using GSON java library?
Now I have only written this piece of code, that returns a list:
String s=getJson("SELECT * FROM address;");
JsonParser jsonParser = new JsonParser();
JsonObject jo = (JsonObject)jsonParser.parse(s);
JsonArray jsonArr = jo.getAsJsonArray("array");
//jsonArr.
Gson googleJson = new Gson();
ArrayList jsonObjList = googleJson.fromJson(jsonArr, ArrayList.class);
System.out.println("List size is : "+jsonObjList.size());
System.out.println("List Elements are : "+jsonObjList.toString());
But the code above works only with JSON object of array, not with string I have shown above.
Could you please try the following and see the results:
// String 's' holds the JSON
JsonParser jsonParser = new JsonParser();
JsonArray jsonArray = (JsonArray) jsonParser.parse(s);
// this object is used to get the keys
JsonObject firstJsonObject = jsonArray.get(0).getAsJsonObject();
Set<java.util.Map.Entry<String, JsonElement>> entrySet = firstJsonObject.entrySet();
// declare two dimensional array
Object[][] array = new Object[entrySet.size()][jsonArray.size() + 1];
// the first column of the two-dimensional array is populated
Iterator<java.util.Map.Entry<String, JsonElement>> itr = entrySet.iterator();
for (int i = 0; itr.hasNext(); i++) {
array[i][0] = itr.next().getKey();
}
// the rest of the columns are populated
for (int i = 0; i < jsonArray.size(); i++) {
JsonObject obj = (JsonObject) jsonArray.get(i);
for (int j = 0; j < array.length; j++) {
String key = array[j][0].toString();
JsonElement value = obj.get(key);
array[j][i + 1] = value instanceof JsonNull ? null : value.getAsString();
}
}
// now the two dimensional array is fully populated

How to extract an array of JSON inside JSON array

{
"hits": [
{
"name": "Google",
"results": [
{
"count": 27495
}
]
},
{
"name": "Yahoo",
"results": [
{
"count": 17707
}
]
}
}
i'am able to read the name and results from the above json by the below code, but unable to print the count value alone from JSON.
JSONObject jsonObject = (JSONObject) jsonParser.parse(reader);
if(null!=jsonObject.get("hits"))
{
System.out.println("Inside IF...");
JSONArray ja = (JSONArray) jsonObject.get("hits");
for(int i=0;i<ja.size() ; i++)
{
System.out.println("Inside FOR...");
JSONObject tempJsonObj = (JSONObject) ja.get(i);
System.out.println(tempJsonObj.get("name").toString());
System.out.println(tempJsonObj.get("results").toString());
}
}
How to extract an array of JSON inside JSON array
Just as you parsed for Outer JSONArray (hits ) . Follow the same for inner ("results") :
JSONObject jsonObject = (JSONObject) jsonParser.parse(reader);
if(null!=jsonObject.get("hits"))
{
System.out.println("Inside IF...");
JSONArray ja = (JSONArray) jsonObject.get("hits");
for(int i=0;i<ja.size() ; i++)
{
System.out.println("Inside FOR...");
JSONObject tempJsonObj = (JSONObject) ja.get(i);
System.out.println(tempJsonObj.get("name").toString());
System.out.println(tempJsonObj.get("results").toString());
JSONArray innerarray = (JSONArray) tempJsonObj.get("results");
for(int i=0;i<innerarray.size() ; i++)
{
JSONObject tempJsoninnerObj = (JSONObject) innerarray.get(i);
System.out.println(tempJsoninnerObj.get("count").toString());
}
}
}

at 0 of type java.lang.String cannot be converted to JSONArray

I am facing this exception at 0 of type java.lang.String cannot be converted to JSONArray don't know why? i have use this before in different work didn't get this exception
List<NameValuePair> pair = new ArrayList<>();
pair.add(new BasicNameValuePair("id", String.valueOf(getitemno)));
json = JSONParser.makeHttpRequest("http://192.168.1.51:80/StopViewApi/index.php","POST",pair);
Log.d("Route Response", json.toString());
int success = 0;
try {
success = json.getInt(TAG_SUCCESS);
Routearrray = new ArrayList<String>();
} catch (JSONException e) {
e.printStackTrace();
}
try {
if (success == 1) {
JSONArray jsonarray;
json = new JSONObject(JSONParser.Result);
JSONArray jArray = json.getJSONArray("data");
for (int i = 0; i <= jArray.length(); i++) {
jsonarray = jArray.getJSONArray(i);
Stopnames = jsonarray.getString(0);
Counter++;
if (Counter <=jArray.length()) {
//Routearrray.add(Stopnames);
Log.d("Stop name:", Stopnames);
//Log.d("Route name:", Routearrray.toString());
} else {
break;
}
}
JSON URL
{
"data":[
"Rawat","Islamabad Mor","Kaak Pull","Lohi Bher","Koral Chowk","Gangal",
"Khana Bridge","Zia Masjid","Kuri Road","Dhok Kala Khan","Faizabad",
"Pirwadhai Mor","Tanki Stop I-8\/4","I-8\/3 Stop","Al Shifa Hospital","AIOU",
"Zero Point","Children Hospital","F-8\/4","Ali Hospital"
],
"success":1,
"status":200,
"status_message":"Login Successfull"
}
Error: at Line
jsonarray = jArray.getJSONArray(i);
From your JSON, jArray is a array of String and not an array of JSONArray.
Replace:
jsonarray = jArray.getJSONArray(i);
Stopnames = jsonarray.getString(0);
with:
Stopnames = jArray.getString(i);
the for loop should be
for (int i = 0; i < jArray.length(); i++) {
You're trying to parse String values as JSONArray. jArray is an array of Strings, not JSONArrays, so all you need to do is just extract the String values from it.
JSONArray jArray = json.getJSONArray("data");
// You already have a JSONArray, now all you need to do is extract String values from it
for (int i = 0; i <= jArray.length(); i++) {
Log.d("Stopnames: " , jArray.getString(i));
....
}
Thats because you "data" is of type json array. whats inside "data" is not a jsonarray, they are just jsonstrings.
change the following lines
jsonarray = jArray.getJSONArray(i);
Stopnames = jsonarray.getString(0);
to
stopnames += jArray.getString(i);
You are trying to get jsonarray from jsonarray, while the json array contains json objects. try this
JSONObject jsonObject = jsonArray.getJSONObject(i)
Stopnames = jsonObject.getString(Integer.toString(i))

Categories