I had gone through a link on parsing Json data on Android, but didnt understand pretty much.
I am getting the following JSON String from my server.
I need to parse it and present it as a listview in my android app. ANy guidance or code snippet.?
Also since my Jason string has data for images, will the listview be able to display it properly?
My JSON String is:
{"results":{"result":[{"year":"2012","title":"The Amazing Spider-Man","details":"http:\/\/www.imdb.com\/title\/tt0948470","director":"Marc Webb","rating":"7.3","cover":"http:\/\/i.media-imdb.com\/images\/SF1f0a42ee1aa08d477a576fbbf7562eed\/realm\/feature.gif"},
{"year":"2014","title":"The Amazing Spider-Man 2","details":"http:\/\/www.imdb.com\/title\/tt0948470","director":"Marc Webb","rating":"7.3","cover":"http:\/\/ia.media-imdb.com\/images\/M\/MV5BMzk3MTE5MDU5NV5BMl5BanBnXkFtZTYwMjY3NTY3._V1._SX54_CR0,0,54,74_.jpg"},
{"year":"2002","title":"Spider-Man","details":"http:\/\/www.imdb.com\/title\/tt0948470","director":"Sam Raimi","rating":"6.3","cover":"http:\/\/ia.media-imdb.com\/images\/M\/MV5BODUwMDc5Mzc5M15BMl5BanBnXkFtZTcwNDgzOTY0MQ##._V1._SX54_CR0,0,54,74_.jpg"},
{"year":"2007","title":"Spider-Man 3","details":"http:\/\/www.imdb.com\/title\/tt1872181","director":"Sam Raimi","rating":"7.5","cover":"http:\/\/ia.media-imdb.com\/images\/M\/MV5BMjE1ODcyODYxMl5BMl5BanBnXkFtZTcwNjA1NDE3MQ##._V1._SX54_CR0,0,54,74_.jpg"},
{"year":"2004","title":"Spider-Man 2","details":"http:\/\/www.imdb.com\/title\/tt1872181","director":"Sam Raimi","rating":"6.8","cover":"http:\/\/i.media-imdb.com\/images\/SFa26455c07afc3c94f52e95de50d5d814\/realm\/tv_series.gif"}]}}
Make Arraylist of All Fields and Write below function to parse above json, it will solve your problem.
ArrayList<String> year, title, details, director, rating, cover;
// For Parse Login Response From Server
public void mParseResponse() throws UnknownHostException {
year=new ArrayList<String>();
title=new ArrayList<String>();
details=new ArrayList<String>();
director=new ArrayList<String>();
rating=new ArrayList<String>();
cover=new ArrayList<String>();
try {
JSONObject jObject = new JSONObject(EntityUtils.toString(entity));
JSONObject jsonobjresults = jObject.getJSONObject("results");
JSONArray jsonarrayresult = jsonobjresults.getJSONArray("result");
for(int i=0;i<jsonarrayresult.length(); i++){
JSONObject mJsonObj = jsonarrayresult.getJSONObject(i);
year.add(mJsonObj.getString("year"));
title.add(mJsonObj.getString("title"));
details.add(mJsonObj.getString("details"));
director.add(mJsonObj.getString("director"));
rating.add(mJsonObj.getString("rating"));
cover.add(mJsonObj.getString("cover"));
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
read this tutorial http://www.javacodegeeks.com/2011/01/android-json-parsing-gson-tutorial.html.
You can use gson library of Google to parse json.
you need to create java classes to store json values
passs that class ref to gson libary. It has simple methods.
chec this doc
Related
{
"Query":"query",
"KMAQuery":"query",
"TotalCount":3,
"Data":[{"CollName":"kmdb_new",
"TotalCount":3,
"Count":3,
"Result":[{"title":"sampletitle",
"director":[{"directorNm":"name1","directorId":"00004544"}],
"nation":"nation1",
"company":"company1",
"genre":"genre1",
"kmdbUrl":"http://www.kmdb.or.kr/vod/vod_basic.asp?nation=K&p_dataid=01040",
"rating":[{"ratingMain":"Y","ratingDate":"19640717","ratingNo":"","ratingGrade":"","releaseDate":"","runtime":""}]]}
Here is my Json Data from OKHttp parsing.
Actually There is many same Result 2~3.
I want to parsing key name "title", "directorNm", "nation", "company", "ratingGrade" and set Model class.
How to parsing multiple Json Object and Array with Gson into Model class?
I'm finally going to use the recyclerview with model class.
If you tell me how to parsing "title" and "directorNm", I can do to rest.
For reference, I am using a AsyncTask, OKHttp, Gson etc.
If you don't understand my question or need code, please comment!
I need your help vigorously.
Here I am sharing the code settting response from Model(Pojo Class)
public void getResponse(JSONObject jsonObject){
try {
JSONObject responseJson = new JSONObject(jsonObject.toString());
JSONArray jsonArray = responseJson.getJSONArray("heroes");
for (int i = 0; i < jsonArray.length(); i++){
//getting the json object of the particular index inside the array
JSONObject jsonObject = jsonArray.getJSONObject(i);
YourPojoClass pojoObject = new YourPojoClass();
pojoObject.setName(jsonObject.getString("name"));
pojoObject.setImageurl(jsonObject.getString("imageurl"));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
I am trying to parse this json.
However, it is not working ...
I want to parse expected_departure_time of all the buses such as 4 , 15, C1, 4A in departure
this is my code which is not working.
try{
String str = response.getString("departures");
JSONArray jsonArray = response.getJSONArray(str);
JSONObject bus = jsonArray.getJSONObject(0);
String four = bus.getString("expected_departure_time");
textView.append(four);
}catch (JSONException e){
e.printStackTrace();
}
JSON
https://transportapi.com/v3/uk/bus/stop/6090282/live.json?app_id=d7180b02&app_key=47b460aac35e55efa666a99f713cff28&group=route&nextbuses=yes
The error you're making is that you're considering "departures" as a JsonArray, which is not the case in your JSON example, it is a JsonObject (Which in my opinion is a poor way of constructing this Json).
Anyway, you will have to get all the JsonObjects inside the "departure" JsonObject by doing this:
try
{
String jsonString=response.toString();
JSONObject jObject= new JSONObject(jsonString).getJSONObject("departures");
Iterator<String> keys = jObject.keys();
while( keys.hasNext() )
{
String key = keys.next();
JSONArray innerJArray = jObject.getJSONArray(key);
//This is your example, you can add a loop here
innerJArray(0).getString("expected_departure_time");
}
}
catch (JSONException e)
{ e.printStackTrace(); }
If you need to use the transport API for other features, to convert JSON strings to Java objects, you can map automatically by using GSON.
Follow the instructions from Leveraging the gson library and map any response you want from this API.
This might be a simple question, so sorry for that. I'm trying to develop a radio app for my internet radio station. I'm using JSON format for the requests (Example JSON) to get information from my station. For example the "title" tag. I want to get this information.
My first try:
JSONObject data = response.getJSONObject("data");
songname.setText(data.getString("title"));
But the problem is that I cannot get this information. What can I do? Thanks in advance.
As your JSON do like this
JSONObject josnOBJ = new JSONObject(response);
JSONArray jArray = josnOBJ.getJSONArray("data");
JSONObject jsonData = null;
String title = null;
for (int i=0; i < jArray.length(); i++)
{
try {
jsonData = jArray.getJSONObject(i);
title= jsonData .optString("title");
} catch (JSONException e) {
// Oops
}
}
songname.setText(title);
You could use some generic JSON parsers instead of manual work. Eg: https://github.com/bajicdusko/AndroidJsonProvider
Just create model class regarding your json content. Check examples in README on github url.
Hope i could help.
You can use GSON library in case you have lot of values to fetch from JSON ,that would take care of everything for you.
Android 2.3.3
I am integrating Twitter API into my android application. I am using Twitter4j.
I could get the tweets for a particular user, using the below code.
Paging paging = new Paging(1, 40);
List<twitter4j.Status> statuses = twitter.getUserTimeline("xxx", paging);
Log.d(Const.TAG,"Showing Timeline.");
for (twitter4j.Status status : statuses) {
String rawJSON = DataObjectFactory.getRawJSON(status);
}
My requirement is that I need to parse the JSON String (rawJSON), to get some other values like, published date and so on.
I am pretty new to JSON parsing esp., with converting things to JSON. All i know in the above code is that, String rawJSON = DataObjectFactory.getRawJSON(status); converts the Status Object to a String and I can view it by logging it.
How do I convert this String to a JSONObject or a JSONArray? Can someone provide me with a sample code?
I tried the below code, but it gives an exception
try {
JSONObject tweet = new JSONObject(rawJSON);
JSONArray textArray = tweet.getJSONArray("text");
String text = textArray.getString(0);
Log.d(Const.TAG, "Text = "+text);
} catch (JSONException e) {
// TODO Auto-generated catch block
Log.d(Const.TAG, "Error while converting string to json");
e.printStackTrace();
}
Here's my code to parse a Twitter4j Status. This example get the language of the tweet.
//Status To JSON String
String statusJson = DataObjectFactory.getRawJSON(status);
//JSON String to JSONObject
JSONObject JSON_complete = new JSONObject(statusJson);
//We get another JSONObject
JSONObject JSON_user = JSON_complete.getJSONObject("user");
//We get a field in the second JSONObject
String languageTweet = JSON_user.getString("lang");
I got a way to get values from Status object without the need to convert it into JSON. Of course this is very basic, by I overlooked it.People who have trouble getting values from Status object, can look at this.
You can get all the values by using the object of Status.
For example, if "status" is an object of Status, we can get the text of the tweet, by using, status.getText() and the user value by using status.user() and so on. Just work on the status object a bit and you will find all the values you need.
I am writing an android application and currently i am getting a JSON reply:
{"Error":"User already exists"}
this is an example of the messages that i get returned
the part that i am after is : "User already exists" and i need to parse it.
The message is currently stored in a string so i would need to convert this to a JSONArray to then convert it to a JSONOject to then be able to call the getString().
what would be the best way to do this?
this may Helps You
String Respones= "{\"Error\":\"User already exists\"}";
try {
JSONObject jobj = new JSONObject(Respones);
String strError = jobj.getString("Error");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I think you can do it directly with JSONTokener and JSONObject if you want ot use default andoid tools.
If you want better, look into the Jackson lib, it's very powerful, open source, kind of standard:
Android JSON Jackson Tutorial
Try this code
JSONArray jsonArray = new JSONArray(ResponseString);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String result = jsonObject.getString("Error").toString().trim();
}