Parsing JSON of a particular case - java
I am trying retrieving the following JSON data from imagga's image recognition API.
{"results":[{"image":"http://docs.imagga.com/static/images/docs/sample/japan-605234_1280.jpg","tagging_id":null,"tags":[{"confidence":63.346307851163395,"tag":"valley"},{"confidence":60.66263009377379,"tag":"mountain"},{"confidence":44.39096006516168,"tag":"canyon"},{"confidence":42.08210930346856,"tag":"landscape"},{"confidence":33.52198895357515,"tag":"geological formation"},{"confidence":32.702112467737216,"tag":"mountains"},{"confidence":28.626223994488203,"tag":"glacier"},{"confidence":28.36,"tag":"natural depression"},{"confidence":28.03481906795487,"tag":"ravine"},{"confidence":27.269738461024804,"tag":"sky"},{"confidence":26.130797131953397,"tag":"rock"},{"confidence":23.11898739400327,"tag":"travel"},{"confidence":21.75182989551758,"tag":"alp"},{"confidence":20.956625061326214,"tag":"national"},{"confidence":20.15360199670358,"tag":"park"},{"confidence":19.826365024393702,"tag":"stone"},{"confidence":19.717420656127437,"tag":"water"},{"confidence":18.049071926896588,"tag":"river"},{"confidence":17.81629840041474,"tag":"hill"},{"confidence":17.30594970410163,"tag":"tourism"},{"confidence":17.192663177192692,"tag":"clouds"},{"confidence":16.53588724897844,"tag":"scenic"},{"confidence":15.98967256769248,"tag":"peak"},{"confidence":15.792599629554461,"tag":"lake"},{"confidence":15.532788988165363,"tag":"scenery"},{"confidence":15.453814687301834,"tag":"snow"},{"confidence":15.232632664896412,"tag":"outdoors"},{"confidence":15.212304004139495,"tag":"range"},{"confidence":15.042325772263556,"tag":"hiking"},{"confidence":14.958759294889424,"tag":"tree"},{"confidence":14.78842712696222,"tag":"forest"},{"confidence":12.853490785491731,"tag":"grass"},{"confidence":12.242518977753525,"tag":"desert"},{"confidence":12.095999999999998,"tag":"natural elevation"},{"confidence":12.03899501602295,"tag":"america"},{"confidence":11.49381779097963,"tag":"environment"},{"confidence":11.250534926394025,"tag":"usa"},{"confidence":10.935999552280517,"tag":"panorama"},{"confidence":10.838870815021957,"tag":"trees"},{"confidence":10.77081532273937,"tag":"south"},{"confidence":10.385222667460749,"tag":"summer"},{"confidence":9.967993711501377,"tag":"cloud"},{"confidence":9.960797892906747,"tag":"wild"},{"confidence":9.840206836878211,"tag":"natural"},{"confidence":9.64736797817423,"tag":"geology"},{"confidence":9.622992778171428,"tag":"rocky"},{"confidence":9.5011692563878,"tag":"outdoor"},{"confidence":9.36921935993258,"tag":"wilderness"},{"confidence":9.360136841263397,"tag":"vacation"},{"confidence":9.295849004816608,"tag":"rocks"},{"confidence":9.200756690906687,"tag":"high"},{"confidence":9.098263071652019,"tag":"highland"},{"confidence":8.912795414022,"tag":"tourist"},{"confidence":8.871604649828521,"tag":"hike"},{"confidence":8.849249986309006,"tag":"landmark"},{"confidence":8.696713373486205,"tag":"cliff"},{"confidence":8.600291951670297,"tag":"scene"},{"confidence":8.535889495009538,"tag":"stream"},{"confidence":8.530021520404471,"tag":"sunny"},{"confidence":8.255077489679804,"tag":"altitude"},{"confidence":8.016191292928964,"tag":"trail"},{"confidence":7.9938748285500605,"tag":"autumn"},{"confidence":7.985278417869093,"tag":"california"},{"confidence":7.927492176055299,"tag":"spain"},{"confidence":7.774043777890904,"tag":"adventure"},{"confidence":7.560207874392119,"tag":"peaceful"},{"confidence":7.485827508554503,"tag":"fall"},{"confidence":7.283862421876644,"tag":"erosion"},{"confidence":7.272123549182718,"tag":"terrain"},{"confidence":7.24510515635207,"tag":"rural"},{"confidence":7.234934522337296,"tag":"vista"},{"confidence":7.092282542389207,"tag":"holiday"}]}]}
I am using http://www.java2s.com/Code/Jar/o/Downloadorgjson20130603jar.htm library.
My Java code is as follows:
String imageUrl = "http://docs.imagga.com/static/images/docs/sample/japan-605234_1280.jpg",
apiKey = "",
apiSecret = "";
// These code snippets use an open-source library. http://unirest.io/java
HttpResponse response = Unirest.get("https://api.imagga.com/v1/tagging")
.queryString("url", imageUrl)
.basicAuth(apiKey, apiSecret)
.header("Accept", "application/json")
.asJson();
String js = response.getBody().toString();
System.out.println(js.toString());
JSONObject jObject = new JSONObject(response.getBody()); // json
System.out.print("hello");
JSONObject data1 = jObject.getJSONObject("results"); // get data
System.out.print(data1); // object
String projectname = data1.getString("tags"); // get the name
// from data.
System.out.print(projectname);
I am getting the error that
Exception in thread "main" org.json.JSONException:
JSONObject["results"] not found.
What I want to get is the list of "tag" and "confidence".
try this
JSONArray data1 = jObject.getJSONArray("results");
Edited Answer
String js = response.getBody().toString();
System.out.println(js.toString());
JSONObject jObject = new JSONObject(js); // json
System.out.print("hello");
JSONArray data1 = jObject.getJSONArray("results");
for(int i = 0; i < data1.length; i++)
{
JSONObject jsonObject = data1.getJSONObject(i);
String projectn ame = jsonObject.getString("tagging_id");
System.out.print(projectname);
JSONArray tagArray = jsonObject.getJsonArray("tags");
for(int j = 0; j < tagArray.length; j++)
{
JSONObject tagObject = tagArray.getJSON(j);
System.out.println("Tag == " + tagObject.getString("tag"));
}
}
To make your life more easy I'd go to model the Objects as POJO's and let Jackson's Objectmapper do the magic.
See http://wiki.fasterxml.com/JacksonDataBinding
I suppose you should try jObject.getJSONArray("results") instead of jObject.getJSONObject("results").
There is also a good tool to convert json to java: http://json2java.azurewebsites.net/
If you use it, you will see:
...other code...
public class RootObject
{
private ArrayList<Result> results;
public ArrayList<Result> getResults() { return this.results; }
public void setResults(ArrayList<Result> results) { this.results = results; }
}
...other code...
And results is list here, so use getJSONArray instead of getJSONObject
If you look into your json results has an array in it and therefore you should use getJSONArray and not getJSONObject.
JSONArray data1 = jObject.getJSONArray("results");
Related
How to use volley in android to extract specific json?
If my request returns a JSON object like this {"autocomplete":["abc", "asd"]} How can I get the array in the JSON and turn it into java ArrayList? I find some methods like getString, getInt. But I don't find a method that could get the array.
val response = JSONObject(yourresponse) val Jarray: JSONArray = response.getJSONArray("autocomplete") for (i in 0 until Jarray.length()) { val jsonobject: JSONObject = jsonarray.getJSONObject(i) Log.e("TAG",jsonobject.toString()) } In this way you can do
String response = new JSONObject(response); JSONArray array= c.getJSONArray("autocomplete"); for (int i = 0; i < array.length(); i++){ JSONObject a = carteVisite.getJSONObject(j); Log.d("TAG", a); }
How to access the JSON element?
#Override protected void onPostExecute(String response) { String firstName = null; String lastName = null; try { JSONObject jsonResponse = new JSONObject(response); JSONArray jsonArray = jsonResponse.getJSONArray(""); JSONObject userInfo = jsonArray.getJSONObject(0); firstName = userInfo.getString("id"); lastName = userInfo.getString("id"); } catch (JSONException e){ e.printStackTrace(); } I have this JSON file https://api.myjson.com/bins/1a5t7w How i can acces to thats values, i used this code but it doesn`t work? It returns #null#
You are getting a JSON array in the response. To parse this array you need to pass the response to JSONArray object like below try { JSONArray rspArr = new JSONArray(response); for(int i= 0; i< rspArr.length(); i++){ JSONObject jsonObject = (JSONObject) rspArr.get(i); //Your logic } }catch (Exception e ){ //log exception }
// since you know is an array, create a JSONArray based on your response String JSONArray array = JSONArray(response) // obtain the first element of your array as a JSONObject JSONObject jsonObject = array.getJSONObject(0) // once you get the jsonObject you can start getting the values you need String id = jsonObject.getString("id") Hope it helps!
Answer by Arunangshu seems correct, you need to extract the JSONArray first because the API is returning JSONArray(array of JSON objects) and not one big JSON object. One can use http://jsonviewer.stack.hu/ for viewing JSON. It gives better understanding of the JSON structure. For Java, one can use http://www.jsonschema2pojo.org/ for converting JSON object(not array) to Java Pojo class (select the options carefully). Following is the first object from json array - {"id":48191,"title":"Apple Crumble Recipe","image":"https://spoonacular.com/recipeImages/48191-312x231.jpg","imageType":"jpg","usedIngredientCount":1,"missedIngredientCount":2,"missedIngredients":[{"id":4073,"amount":35.0,"unit":"g","unitLong":"grams","unitShort":"g","aisle":"Milk, Eggs, Other Dairy","name":"margarine","original":"35 g margarine or butter","originalString":"35 g margarine or butter","originalName":"margarine or butter","metaInformation":[],"meta":[],"image":"https://spoonacular.com/cdn/ingredients_100x100/butter-sliced.jpg"},{"id":8120,"amount":35.0,"unit":"g","unitLong":"grams","unitShort":"g","aisle":"Cereal","name":"rolled oats","original":"35 g rolled oats","originalString":"35 g rolled oats","originalName":"rolled oats","metaInformation":[],"meta":[],"image":"https://spoonacular.com/cdn/ingredients_100x100/rolled-oats.jpg"}],"usedIngredients":[{"id":9003,"amount":400.0,"unit":"g","unitLong":"grams","unitShort":"g","aisle":"Produce","name":"apples","original":"400 g cooking apples peeled cored and quartered","originalString":"400 g cooking apples peeled cored and quartered","originalName":"cooking apples peeled cored and quartered","metaInformation":["cored","peeled","quartered"],"meta":["cored","peeled","quartered"],"image":"https://spoonacular.com/cdn/ingredients_100x100/apple.jpg"}],"unusedIngredients":[],"likes":965}
Loop through JSON to get certain values
I need to loop through a JSON and get the following information: The original title, overview, release date, poster_path. I have the following code.. #Override protected void onPostExecute(String s) { try { JSONObject jsonObject = new JSONObject(result); JSONArray jArray = jsonObject.getJSONArray("results"); JSONObject json_data = null; for (int i = 0; i < jArray.length(); i++) { JSONObject finalObject = jArray.getJSONObject(i); String movie_title = finalObject.getString("title"); String releaseDate = finalObject.getString("release_date"); mMovie_title.setText(movie_title); mReleaseDate.setText(releaseDate); } super.onPostExecute(s); } catch (JSONException e) { e.printStackTrace(); } } The problem with this code is that it only gets me the final movie in the array. It does not print any other movie titles out. What I need to do is fetch the movie titles from the JSON along with the overview, release dates & poster path. Here is the JSON.. https://api.themoviedb.org/3/movie/top_rated?api_key=f1d314280284e94ff7d1feeed7d44fdf&language=en-US&page=1 Any help is much appreciated.
mMovie_title.setText(movie_title); mReleaseDate.setText(releaseDate); It looks like you are re-assigning the same variable everytime. That's why you only get the last element. You should probably have a StringBuilder StringBuilder titles = new StringBuilder(); for ... { ... titles.append(movie_title); } mMovie_title.setText(titles.toString());
It's not a good decision to loop the JSON. Try to use GSON The performance is better than that and also it's a very good practice Gson is a Java library that can be used to convert Java Objects into their JSON representation. It can also be used to convert a JSON string to an equivalent Java object. Nice coding!
If you want to store multiple movie titles then you need a few things. First, you need a movie object to hold the values of the movie titles and the movie dates. Something like: public class Movie { private String movieTitle; private String releaseDate; public Movie(String movieTitle, String releaseDate) { super(); this.movieTitle = movieTitle; this.releaseDate = releaseDate; } } Then you need to have a list of movies. super.onPostExecute(s); List<Movie> movies = new ArrayList<Movie>(); Movie movie = null; try { JSONObject jsonObject = new JSONObject(result); JSONArray jArray = jsonObject.getJSONArray("results"); JSONObject json_data = null; for (int i = 0; i < jArray.length(); i++) JSONObject finalObject = jArray.getJSONObject(i); String movie_title = finalObject.getString("title"); String releaseDate = finalObject.getString("release_date"); movies.add(new Movie(movie_title, releaseDate)); } } catch (JSONException e) { e.printStackTrace(); } // Do something with movies // example :: for (Movie movie : movies) { textView.setText(movie.getMovieTitle); // etc... }
How to parse JSON structured-JSON Array Object in Java
i'm trying to parse this JSON code { "resultCode":"350", "message":"OK", "result":1, "data": { "totalCount":"2", "videos":[ { "videoId":"73bfedf534", "VideoUrl":"www.videourlexample.com", "title":"vbsample1", "description":"" }, { "videoId":"73bfedf534", "VideoUrl":"www.videourlexample.com", "title":"vbsample2", "description":"" } ] } } I was able to parse only this. "resultCode":"350", "message":"OK", "result":1, this is the java code JSONObject jsonObject = (JSONObject) //return the JSON code above. jsonParser.parse(getHTML("...httpRequest...")); // get a String from the JSON object String resultCode = (String) jsonObject.get("resultCode"); System.out.println("[RESULTCODE] The message is: " + resultCode); // get a String from the JSON object String message = (String) jsonObject.get("message"); System.out.println("[MESSAGE] The message is: " + message); // get a number from the JSON object long result = (long) jsonObject.get("result"); System.out.println("[RESULT] The resultCode is: " + result); I can't parse the "data". Someone can help me? I would like to take each value from the json array separately... like resultCode, message and result. Thank you.
JSONObject mainObj= new JSONObject(yourJSON); String resultCode= mainObj.get("resultCode"); String message= mainObj.get("message"); String result= mainObj.get("result"); JSONObject dataObj = mainObj.get("data"); JSONArray jsonArray = (JSONArray) dataObj.get("videos"); for (int i = 0; i <jsonArray.length(); i++) { JSONObject obj= jsonArray.get(i); String videoId=obj.get("videoId"); String videoUrl=obj.get("VideoUrl"); String title=obj.get("title"); String description=obj.get("description"); System.out.println("videoId="+videoId +"videoUrl="+videoUrl+"title=title"+"description="+description); } System.out.println("resultCode"+resultCode+"message"+message+"result"+result);
You can try using this:- JSONObject dataObj = (JSONObject)dataObj .get("data"); JSONArray jsonArray = (JSONArray) dataObj.get("videos"); for (int i = 0; i <jsonArray.length(); i++) { System.out.println(((JSONObject)jsonArray.get(i)).get("videoUrl")); } Currently I have just printes videoUrl, you can similarly get other attributes for videos.
for data use: int totalCount = (int) ((Map) jsonObject.get("data")).get("totalCount"); JSONArray videos = (JSONArray) jsonObject.get("data")).get("videos"); and then parse videos JSONArray.
Getting Json object inside a Json object in Java
So I have some code that is able to send this out: {"id":1, "method":"addWaypoint", "jsonrpc":"2.0", "params":[ { "lon":2, "name":"name", "lat":1, "ele":3 } ] } The server receives this JSON object as a string named "clientstring": JSONObject obj = new JSONObject(clientstring); //Make string a JSONObject String method = obj.getString("method"); //Pulls out the corresponding method Now, I want to be able to get the "params" value of {"lon":2,"name":"name","lat":1,"ele":3} just like how I got the "method". however both of these have given me exceptions: String params = obj.getString("params"); and JSONObject params = obj.getJSONObject("params"); I'm really at a loss how I can store and use {"lon":2,"name":"name","lat":1,"ele":3} without getting an exception, it's legal JSON yet it can't be stored as an JSONObject? I dont understand. Any help is VERY appreciated, thanks!
params in your case is not a JSONObject, but it is a JSONArray. So all you need to do is first fetch the JSONArray and then fetch the first element of that array as the JSONObject. JSONObject obj = new JSONObject(clientstring); JSONArray params = obj.getJsonArray("params"); JSONObject param1 = params.getJsonObject(0);
How try like that JSONObject obj = new JSONObject(clientstring); JSONArray paramsArr = obj.getJSONArray("params"); JSONObject param1 = paramsArr.getJSONObject(0); //now get required values by key System.out.println(param1.getInt("lon")); System.out.println(param1.getString("name")); System.out.println(param1.getInt("lat")); System.out.println(param1.getInt("ele"));
Here "params" is not an object but an array. So you have to parse using: JSONArray jsondata = obj.getJSONArray("params"); for (int j = 0; j < jsondata.length(); j++) { JSONObject obj1 = jsondata.getJSONObject(j); String longitude = obj1.getString("lon"); String name = obj1.getString("name"); String latitude = obj1.getString("lat"); String element = obj1.getString("ele"); }