Loop through JSON to get certain values - java

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

Related

Avoiding duplicates while adding jsonobjects into the jsonarray using java

I have a list of objects and am converting into JSONArray. Am iterating over the JSONObjects and making an array of JSONObjects.
Now, i want to avoid duplicates objects to get insert into the JSONArray.
Please find my java code below.
JSONArray responseArray1 = new JSONArray();
if (!itemList.isEmpty())
{
jsonArray = new JSONArray(itemList);
for (int i = 0; i < jsonArray.length(); i++)
{
JSONObject jsonObj = jsonArray.getJSONObject(i);
JSONObject responseObj = new JSONObject();
String attr_label = jsonObj.optString("attr_label");
if(StringUtils.equalsIgnoreCase(attr_label, "long_description")) {
long_description = jsonObj.optString("value");
}
else if(StringUtils.equalsIgnoreCase(attr_label, "description")) {
description = jsonObj.optString("value");
}
responseObj.put("id", jsonObj.opt("id")); // i will get duplicate id
responseObj.put("code", jsonObj.opt("code")); // i will get duplicate code
responseObj.put("long_description", long_description);
responseObj.put("description", description);
responseArray1.put(responseObj);
}
}
Please find my actual jsonArray :
[
{
"code":"xyaz",
"attr_label":"long_description",
"id":"12717",
"value":"Command Module"
},
{
"code":"xyaz",
"attr_label":"description",
"id":"12717",
"value":"Set Point Adjustment"
},
]
Am expecting like the below jsonArray :
[
{
"code":"xyaz",
"id":"12717",
"long_description":"Command Module"
"description" : "Set Point Adjustment"
}
]
Update :
I have tried with the below code to avoid duplicate insertion of id & code field. but is not working properly. Its inserting duplicates also.
List<String> dummyList=new ArrayList<String>();
JSONArray responseArray2 = new JSONArray(itemList);
if (!itemList.isEmpty())
{
jsonArray = new JSONArray(itemList);
for (int i = 0; i < jsonArray.length(); i++)
{
JSONObject jsonObj = jsonArray.getJSONObject(i);
JSONObject responseObj = new JSONObject();
String itemCode = jsonObj.optString("code");
String id = jsonObj.optString("id");
if(!dummyList.contains(itemCode) && !dummyList.contains(id) ) {
dummyList.add(String.valueOf(jsonObj.opt("id")));
dummyList.add(String.valueOf(jsonObj.opt("code")));
responseObj.put("id", jsonObj.opt("id"));
responseObj.put("code", jsonObj.opt("code"));
responseObj.put("long_description", long_description);
responseObj.put("description", description);
responseArray2.put(responseObj);
}
}
}
Make a temporary array list and add unique code in that arrayList and check if it already exists in arrayList then don't put this again
String code = jsonObj.opt("code");
if(!arrayList.contains(code))
{
arrayList.add(code);
responseObj.put("id", jsonObj.opt("id"));
responseObj.put("code", jsonObj.opt("code"));
responseObj.put("long_description", long_description);
responseObj.put("description", description);
}
use TreeSet and add Comparator to their constructor in which it compare the duplicate data of the object.
for example:-
Set<Sample> sampleSet=new TreeSet<>(new Sample());
where Sample Class look like:-
class Sample implements Camparator<Sample>{
private String name;
private String id;
//getter
//setter
#Override
public String compare(Sample o1,Sample o2){
return o1.getName.compareTo(o2.getName);
}
}
This will give a set of unique name entries.

Parsing JSON of a particular case

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

Android get data from json and sort

I'm trying to get data from json. I can get data at first state.
But how to get data "ascending" and "descending" and show it on another activity in listview ?
Here's My Json
[{"category_name":"Food","filter_type":"Sort by","field_name":"","type":"VALUE","table_name":"","item_list":["Ascending","Descending"]}
And here's my Java code
if (jsonStr != null) {
try {
foods = new JSONArray(jsonStr);
// looping through All Contacts
for (int i = 0; i < foods.length(); i++) {
JSONObject c = foods.getJSONObject(i);
if(c.getString("category_name").equals("Food")) {
String category_name = c.getString(TAG_CATEGORY_NAME);
String table_name = c.getString(TAG_TABLE_NAME);
String item_list = c.getString(TAG_ITEM_LIST);
// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
contact.put(TAG_CATEGORY_NAME, category_name);
contact.put(TAG_TABLE_NAME, table_name);
contact.put(TAG_ITEM_LIST, item_list);
// adding contact to contact list
foodlistfilter.add(contact);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
I'm trying to follow this tutorial http://www.androidhive.info/2012/01/android-json-parsing-tutorial/, but i still don't fully understand.
Let me explain this.
[ means its an array.
{ is an object.
In your case it's an array whcih contains an -JSONObject with name category_name, filter_type and field_name. type and table_name and a new jsonarray with object item_list.
How can you parse this string?
Here is an example:
String str = "[{"category_name":"Food","filter_type":"Sort by","field_name":"","type":"VALUE","table_name":"","item_list":["Ascending","Descending"]}";
JSONArray jsonArray = new JSONArray(str);
//now it holds the JSONObject.
for (int i = 0; i<= jsonArray.length(); i++) {
//now we loop through and get the jsonObject
JSONObject jsonObj = new JSONObject(jsonArray.getJsonObject(i));
//now it contains your data.
Log.d("Category_nameValue=", jsonObj.getString("category_name"));
//now we want to get the array from the item_list.
JSONArray itemList = new JSONArray(jsonObj.getString("item_list"));
//now itemList.getString(1); === Ascending while itemList.getString(2) == Descending
//now itemList contains several new objects which can also be looped as the parent one.
}
Since you now know how to create an JSONArray, you can start sorting it.
This has been answered already at Android how to sort JSONArray of JSONObjects
If you want to send those data to another Activity you can use the JSONArray.toString() method and send it via Intents.
This is easy explained at Pass a String from one Activity to another Activity in Android
Hope this helps.
If you're new, I would recommend you think about using Gson to parse your Json response directly to a java entity class. So you will avoid to manually parse all your responses.
Your JSON response
[{"category_name":"Food","filter_type":"Sort by","field_name":"","type":"VALUE","table_name":"","item_list":["Ascending","Descending"]}
The entity representing the response
public class MyEntity {
String category_name;
String filter_type;
String field_name;
String type;
String table_name;
String [] item_list;
// getters / setters ...
}
Parsing the response
Gson gson = new Gson();
MyEntity myEntity = gson.fromJson(response, MyEntity.class);
Finally, to send the data, start the new Activity with extras
Intent intent = new Intent(this, AnotherActivity.class);
intent.putExtra("EXTRA_DATA", myEntity.getCategoryName());
startActivity(intent);
Now you recover the extra data on your AnotherActivity
Intent intent = getIntent();
String categoryName = intent.getStringExtra("EXTRA_DATA");
And you can fill the ListView using an ArrayAdapter: Example
To get a JSONArray from your JSONObject c
simply write:
JSONArray itemList = c.getJSONArray(name);
then you can iterate through that data like any other array
for (int i = 0; i < itemList.length(); i++) {
// do something
}

Parse json array from webserver

I'm going to parse a json array from web server to android app.The array looks like this
{"Level":
[
{"route":[{"lat":38.889762,"lgn":-77.081764},
{"lat":38.89096,"lgn":-77.081916}]},
{"route":[{"lat":38.889762,"lgn":-77.081764},
{"lat":38.89096,"lgn":-77.081916}]},
{"route":[{"lat":38.889762,"lgn":-77.081764},
{"lat":38.89096,"lgn":-77.081916}]}
]
}
my java code is
JSONObject json = new JSONObject(result);
JSONArray jArray = json.getJSONArray("Level");
rlevel = new ArrayList<LatLng>();
System.out.println("*****JARRAY*****"+jArray.length());
for(int i=0;i<jArray.length();i++){
JSONObject json_data = jArray.getJSONObject(i);
jlat = json_data.getDouble("lat");
jlgn = json_data.getDouble("lgn");}
but not works! any idea?after this i want to save each route into an array (etc $plan[1]=first route from json, $plan[2]=second route from json)
Try something like this:
//code is a String where you saved the json
JSonObject json= new JsonParser().parse(code).getAsJsonObject();
JsonArray jArray= json.getAsJsonArray("Level");
rLevel=new ArrayList<LatLng>();
//notice the use of the size() method. There is not length() method defined for ArrayList
System.out.println("*****JARRAY*****"+jArray.size());
for(int i=0;i<jArray.size();i++){
//notice that inside the Level Array you have route-arrays
JSonObject level_item = jArray.get(i).getAsJsonObject();
JSonArray route= level_item.getAsJSonArray("route");
//now I don't know exactly what data you want to extract, since there are 2
//pairs of LatLng, for the first one:
jlat = route.get(0).get("lat").getAsDouble();
jlgn= route.get(0).get("lgn").getASDouble();
The exact names for methods and JsonObjects tend to differ from a library to another, but the principle is the same.
This parse task can be done very easily using droidQuery:
try {
JSONObject json = $.parseJSON(result);
if (json.has("Level")) {
Object[] datas = $.makeArray(json.getJSONArray("Level"));
for (Object data : datas) {
JSONObject obj = (JSONObject) data;
Object[] coordinates = $.makeArray(obj.getJSONArray("route"));
for (Object coord : coordinates) {
Map<String, ?> map = $.map((JSONObject) coord);
double latitude = (Double) map.get("lat");
double longitude = (Double) map.get("lgn");
//TODO: do something with these values
}
}
}
else {
Log.d("JSON", "Result does not contain 'Levels' variable");
}
}
catch (Throwable t) {
t.printStackTrace();
}

How to convert JSON formatted string of data rows of a table in to java array in android

I have a JSON string like this of data for a table in an android app. one of {} is a row of data for the table. I want to separate these {}s into an array and then each element inside this array into other sub-arrays separating other elements inside {}. Please suggest an appropriate way of accomplishing this criteria using JSON. Thank you.
[
{
"nodeName":"prime_mtsc22#smpp3",
"nodeId":"MTSC3",
"tidPrefix":"4",
"optStatus":"offline",
"daStart":"1",
"daEnd":"3",
"description":"Description"
},
{
"nodeName":"prime_mtsc22#smpp2",
"nodeId":"MTSC58",
"tidPrefix":"1",
"optStatus":"blocked",
"daStart":"5",
"daEnd":"10",
"description":"new description"
},
{
"nodeName":"prime_mtsc22#smpp1",
"nodeId":"MTSC1",
"tidPrefix":"15",
"optStatus":"online",
"daStart":"12",
"daEnd":"20",
"description":"Description"
},
{
"nodeName":"prime_mtsc22#smpp0",
"nodeId":"MTSC15",
"tidPrefix":"15",
"optStatus":"offline",
"daStart":"25",
"daEnd":"30",
"description":"Description"
}
]
ok so in that case the code to use is this
String jsonString = <your jsonString>;
// THIS IS NOT NEEDED ANYMORE
//JSONObject json = new JSONObject(jsonString);
JSONArray topArray = null;
try {
// Getting your top array
// THIS IS NOT NEEDED ANYMORE
//topArray = json.getJSONArray(jsonString);
//use this instead
topArray = new JSONArray(jsonString);
// looping through All elements
for(int i = 0; i < topArray.length(); i++){
JSONObject c = topArray.getJSONObject(i);
//list holding row data
List<NodePOJO> nodeList = new ArrayList<NodePOJO>();
// Storing each json item in variable
String nodeName = c.getString("nodeName");
String nodeID = c.getString("nodeID");
NodePOJO pojo = new NodePOJO();
pojo.setNodeName(nodeName);
//add rest of the json data to NodePOJO class
//the object to list
nodeList.add(pojo);
}
} catch (JSONException e) {
e.printStackTrace();
}
ok?
Use JSONObject for this http://developer.android.com/reference/org/json/JSONObject.html
Example
String jsonString = <your jsonString>;
JSONObject json = new JSONObject(jsonString);
JSONObject topArray = ;
try {
// Getting your top array
topArray = json.getJSONArray(TAG_ARRAY_TOP);
// looping through All elements
for(int i = 0; i < topArray.length(); i++){
JSONObject c = topArray.getJSONObject(i);
//list holding row data
List<NodePOJO> nodeList = new ArrayList<NodePOJO>();
// Storing each json item in variable
String nodeName = c.getString("nodeName");
String nodeID = c.getString("nodeID");
NodePOJO pojo = new NodePOJO();
pojo.setNodeName(nodeName);
//add rest of the json data to NodePOJO class
//the object to list
nodeList.add(pojo);
}
} catch (JSONException e) {
e.printStackTrace();
}
Use the NodePOJO class to hold each row values.
public class NodePOJO {
private String nodeName;
// do for rest of the json row data
public void setNodeName(String nodeName) {
this.nodeName = nodeName;
}
public String getNodeName() {
return this.nodeName;
}
}

Categories

Resources