{
"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());
}
}
}
Related
This is JSON file. I want make java can produce like this json. Just ignore the value, What i want is the structure of the json.
{
"Car": [
{
"CarId": 123,
"Status": "Ok"
},
{
"CarId": 124,
"Status": "ok"
}
],
"Motor": [
{
"MotorId": 3,
"DriverId": 174
},
{
"MotorId": 3,
"DriverId": 174
}
],
"Bus": [
{
"BusId": 8,
"Status": 3
},
{
"BusId": 9,
"Status": 2
}
]
}
This is my java code.
JSONObject motorObject = new JSONObject();
JSONObject busObject = new JSONObject();
JSONObject carObject = new JSONObject();
JSONArray motorArray = new JSONArray();
JSONArray busArray = new JSONArray();
JSONArray carArray = new JSONArray();
motorArray.put(motorTracks.getJSONObject());
busArray.put(buss.getJSONObject());
try
{
motorObject.put("Motor",motorArray);
busObject.put("Bus",busArray);
carArray.put(MotorObject);
carArray.put(stepObject);
carObject.put("Car",dataArray);
} catch (JSONException e)
{
e.printStackTrace();
}
The output is :
{
"Car": [
{
"Motor": [
{
"MotorId": 0,
"DriverId": 0
}
]
},
{
"Bus": [
{
"BusId": 0,
"Status": 0
}
]
}
]
}
For value, it's okay, just ignore the value, but what i want how can i get structure like the json file.
Use this code and Enjoy :)
private void createJsonStructure() {
try
{
JSONObject rootObject = new JSONObject();
JSONArray carArr = new JSONArray();
for (int i = 0; i < 2 ; i++)
{
JSONObject jsonObject = new JSONObject();
jsonObject.put("CarId", "123");
jsonObject.put("Status", "Ok");
carArr.put(jsonObject);
}
rootObject.put("Car", carArr);
JSONArray motorArr = new JSONArray();
for (int i = 0; i < 2 ; i++)
{
JSONObject jsonObject = new JSONObject();
jsonObject.put("MotorId", "123");
jsonObject.put("Status", "Ok");
motorArr.put(jsonObject);
}
rootObject.put("Motor", motorArr);
JSONArray busArr = new JSONArray();
for (int i = 0; i < 2 ; i++)
{
JSONObject jsonObject = new JSONObject();
jsonObject.put("BusId", "123");
jsonObject.put("Status", "Ok");
busArr.put(jsonObject);
}
rootObject.put("Bus", busArr);
Log.e("JsonObject", rootObject.toString(4));
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
JSONObject motorObject = new JSONObject();
JSONObject busObject = new JSONObject();
JSONObject carObject = new JSONObject();
JSONObject wholeObject =new JSONObject();
JSONArray motorArray = new JSONArray();
JSONArray busArray = new JSONArray();
JSONArray carArray = new JSONArray();
motorArray.put(motorTracks.getJSONObject());
busArray.put(buss.getJSONObject());
carArray.put(car.getJSONObject());
try
{
wholeObject.put("Motor",motorArray);
wholeObject.put("Bus",busArray);
wholeObject.put("Car",carArray);
System.out.println(wholeObject);
}
catch (JSONException e)
{
e.printStackTrace();
}
I'm trying to parse a JSON object in java :
{
"poster_path": "/e3QX3tY0fBR1GuxdP0mwpN16cqI.jpg",
"adult": false,
"overview": "In 1950s Pittsburgh, a frustrated African-American father struggles with the constraints of poverty, racism, and his own inner demons as he tries to raise a family.",
"release_date": "2016-12-16",
"genre_ids": [
18
],
"id": 393457,
"original_title": "Fences",
"original_language": "en",
"title": "Fences",
"backdrop_path": "/jNlCIAcheh0iOuL3kz9x1Wq9WLG.jpg",
"popularity": 10.976374,
"vote_count": 290,
"video": false,
"vote_average": 6.7
},
But I get a JSONException when I try to access the values for poster_path(org.json.JSONException: No value for poster_path) and release_date(org.json.JSONException: No value for release_date)
ArrayList<MovieModel> results = new ArrayList<MovieModel>();
String streamAsString = result;
try{
JSONObject jsonObject = new JSONObject(streamAsString);
JSONArray array = (JSONArray) jsonObject.get("results");
for (int i = 0; i < array.length(); i++) {
JSONObject c = array.getJSONObject(i);
JSONObject jsonMovie = array.getJSONObject(i);
MovieModel movieModel= new MovieModel();
movieModel.setMovieTitle(jsonMovie.getString("title"));
movieModel.setMovieGenre("na");;
String strImgURL=jsonObject.getString("poster_path").substring(2);
movieModel.setImgURL("");
movieModel.setMovieYear(jsonObject.getString("release_date"));
results.add((movieModel));
}
}
catch(JSONException j)
{
System.err.println(j);
Log.d(DEBUG_TAG, "Error parsing JSON. String was: " + j.toString());
}
Not sure what could be causing this error
You're trying to get the poster_path and release_date values from the outer JSONObject, the one that has everything (including the JSONArray that contains the individual movies).
In the loop, just use jsonMovie instead of jsonObject:
for (int i = 0; i < array.length(); i++) {
JSONObject jsonMovie = array.getJSONObject(i);
MovieModel movieModel= new MovieModel();
movieModel.setMovieTitle(jsonMovie.getString("title"));
movieModel.setMovieGenre("na");
String strImgURL=jsonMovie.getString("poster_path").substring(2);
movieModel.setImgURL("");
movieModel.setMovieYear(jsonMovie.getString("release_date"));
results.add((movieModel));
}
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();
I am getting the following as a String response from a webserveice:
[
[
{
"dgtype": "adhoc",
"subtypename": "Person",
"subtypedesc": "null",
"summary": "Junaid (Self)",
"subtype": "person",
"birthdate": "1995-1-23 ",
"name": "Junaid (Self)"
},
{
"dgtype": "adhoc",
"subtypename": "Job",
"subtypedesc": "null",
"summary": "Exa",
"subtype": "person",
"birthdate": "2010-01-30",
"name": "Junaid (Self)"
}
]
]
In Java I am trying to do the following:
JSONArray jArray = new JSONArray(result);
System.out.println("Response: "+jArray);
for(int i = 0; i<= jArray.length(); i++){
try {
JSONObject oneObject = jArray.getJSONObject(i);
String dgtype = oneObject.getString("dgtype");
String subtypename = oneObject.getString("subtypename");
String subtypedesc = oneObject.getString("subtypedesc");
String summary = oneObject.getString("summary");
String subtype = oneObject.getString("subtype");
String birthdate = oneObject.getString("birthdate");
String name = oneObject.getString("name");
System.out.println(i);
System.out.println("dgtype: "+dgtype);
System.out.println("subtypename: "+subtypename);
System.out.println("subtypedesc: "+subtypedesc);
System.out.println("summary: "+summary);
System.out.println("subtype: "+subtype);
System.out.println("birthdate: "+birthdate);
System.out.println("name: "+name);
} catch (JSONException e) {
System.out.println("JSON Exception: "+e);
}
}
However I am getting the following exception:
JSON Exception: org.json.JSONException: Value
[
{
"dgtype": "adhoc",
"subtypename": "Person",
"subtypedesc": "null",
"summary": "Junaid (Self)",
"subtype": "person",
"birthdate": "1995-1-23 ",
"name": "Junaid (Self)"
},
{
"dgtype": "adhoc",
"subtypename": "Job",
"subtypedesc": "null",
"summary": "Exa",
"subtype": "person",
"birthdate": "2010-01-30",
"name": "Junaid (Self)"
}
]
at 0 of type org.json.JSONArray cannot be converted to JSONObject
JSON Exception: org.json.JSONException: Index 1 out of range [0..1)
I am following this example. Where am I going wrong? Also notice the missing long brackets in the exception snippet.
You have two arrays, one is within another:
[
[
//Your objects
]
]
You could either change data format so it only has one array, or modify your code:
JSONArray outer = new JSONArray(result);
JSONArray jArray = outer.getJSONArray(0);
jArray JSONArray contain another JSONArray which contain JSONObeject so first get JSONArray and then get all JSONObject from it:
JSONArray oneArray = jArray.getJSONArray(i);
for(int j = 0; j<= oneArray.length(); j++){
JSONObject oneObject = oneArray.getJSONObject(j);
// get dgtype,subtypename,subtypedesc,.. from oneObject
}
As it says, 'JSONArray cannot be converted to JSONObject', You have an array in another array, so
JSONArray jArray1 = new JSONArray(result);
then
JSONArray jArray = jArray1.getJSONArray(0);
Now it will work.
for(int i = 0; i<= jArray.length(); i++){
final JSONArray innerArray = jArray.getJSONArray(i);
for (int a = 0; a < innerArray.length(); a++) {
try {
final JSONObject oneObject = innerArray.getJSONObject(i);
String dgtype = oneObject.getString("dgtype");
String subtypename = oneObject.getString("subtypename");
String subtypedesc = oneObject.getString("subtypedesc");
String summary = oneObject.getString("summary");
String subtype = oneObject.getString("subtype");
String birthdate = oneObject.getString("birthdate");
String name = oneObject.getString("name");
System.out.println(i);
System.out.println("dgtype: "+dgtype);
System.out.println("subtypename: "+subtypename);
System.out.println("subtypedesc: "+subtypedesc);
System.out.println("summary: "+summary);
System.out.println("subtype: "+subtype);
System.out.println("birthdate: "+birthdate);
System.out.println("name: "+name);
} catch (JSONException e) {
System.out.println("JSON Exception: "+e);
}
}
}
In the Result String i have entire data for that i'm parsing ,i need to print Current Conditions inside values.
current_condition": [ {"cloudcover": "75", "humidity": "71", "observation_time": "06:55 AM", "precipMM": "0.6", "pressure": "1009", "temp_C": "32", "temp_F": "90", "visibility": "10", "weatherCode": "116", "weatherDesc": [ {"value": "Partly Cloudy" } ], "weatherIconUrl": [ {"value": "http:\/\/cdn.worldweatheronline.net\/images\/wsymbols01_png_64\/wsymbol_0002_sunny_intervals.png" } ], "winddir16Point": "S", "winddirDegree": "170", "windspeedKmph": "9", "windspeedMiles": "6" } ]
This is my json array ,here i need cloudcover ,weatherDescarrays inside values,how can i print those values.
Here what i did is
JSONParser parser = new JSONParser();
Object obj1 = parser.parse(Result);
JSONObject jobj = (JSONObject) obj1;
JSONObject dataResult = (JSONObject) jobj.get("data");
JSONArray current_condition = (JSONArray) dataResult.get("current_condition");
//out.println(current_condition);
for (int i = 0; i < current_condition.size(); i++) {
}
inside for loop how to repeat and print values ,could anybody help me,thanks in advance.
Assuming that you are using org.json, I would iterate over the array as follows:
public static void main(String[] args) {
String json = "{ \"data\": { \"current_condition\": [ {\"cloudcover\": \"75\", \"humidity\": \"71\", \"observation_time\": \"06:55 AM\", \"precipMM\": \"0.6\", \"pressure\": \"1009\", \"temp_C\": \"32\", \"temp_F\": \"90\", \"visibility\": \"10\", \"weatherCode\": \"116\", \"weatherDesc\": [ {\"value\": \"Partly Cloudy\" } ], \"weatherIconUrl\": [ {\"value\": \"http:\\/\\/cdn.worldweatheronline.net\\/images\\/wsymbols01_png_64\\/wsymbol_0002_sunny_intervals.png\" } ], \"winddir16Point\": \"S\", \"winddirDegree\": \"170\", \"windspeedKmph\": \"9\", \"windspeedMiles\": \"6\" } ]}}";
try {
JSONObject jObj = new JSONObject(json);
JSONObject dataResult = jObj.getJSONObject("data");
JSONArray jArr = (JSONArray) dataResult.getJSONArray("current_condition");
for(int i = 0; i < jArr.length();i++) {
JSONObject innerObj = jArr.getJSONObject(i);
for(Iterator it = innerObj.keys(); it.hasNext(); ) {
String key = (String)it.next();
System.out.println(key + ":" + innerObj.get(key));
}
}
}
catch (JSONException e) {
e.printStackTrace();
}
}
Are you using json simple?, if yes, then try :
for (JSONObject object : current_condition) {
System.out.println("cloudcover : " + object.get("cloudcover"));
System.out.println("humidity : " + object.get("humidity"));
}