I have a long string from android Http get like this:
{"movies":[
{"movieId":"fmen71229238","eTitle":"Mission: Impossible - Ghost Protocol","cTitle":"不可能的任務:鬼影行動","imageUrl":"http://test.mobibon.com.tw/MovieGoTest/Pics/pl_fmen7122923814_s.jpg","releaseDate":"2011/12/15","saleType":"0"},
{"movieId":"fstw79905171","eTitle":"Seediq Bale","cTitle":"賽德克.巴萊(上)太陽旗","imageUrl":"http://test.mobibon.com.tw/MovieGoTest/Pics/pl_fstw7990517114_s.jpg","releaseDate":"2011/9/9","saleType":"0"},
{"movieId":"fytw91390391","eTitle":"You Are the Apple of My Eye","cTitle":"那些年,我們一起追的女孩","imageUrl":"http://test.mobibon.com.tw/MovieGoTest/Pics/pl_fytw9139039102_s.jpg","releaseDate":"2011/8/19","saleType":"0"}
]}
the string is JSON format, and I want it be sort in different array,and display in a Listview, so I used the JSON paser like this
JSONArray result = new JSONArray(retSrc);
for(int i = 0;i < result.length(); i++)
{
JSONObject stock_data = result.getJSONObject(i);
Log.i("bird","eTitle:"+stock_data.getString("eTitle"));
}
} finally {
}
}
p.s retSrc is the long string from site
But the Log
Log.i("bird","eTitle:"+stock_data.getString("eTitle"));
logs nothing.
I expect it log like this:
Mission: Impossible - Ghost Protocol Seediq Bale.....etc
here is the code to parse it
String jsonData = "{\"movies\":["
+ "{\"movieId\":\"fmen71229238\",\"eTitle\":\"Mission: Impossible - Ghost Protocol\",\"cTitle\":\"??????:????\",\"imageUrl\":\"http://test.mobibon.com.tw/MovieGoTest/Pics/pl_fmen7122923814_s.jpg\",\"releaseDate\":\"2011/12/15\",\"saleType\":\"0\"},"
+ "{\"movieId\":\"fstw79905171\",\"eTitle\":\"Seediq Bale\",\"cTitle\":\"???.??(?)???\",\"imageUrl\":\"http://test.mobibon.com.tw/MovieGoTest/Pics/pl_fstw7990517114_s.jpg\",\"releaseDate\":\"2011/9/9\",\"saleType\":\"0\"},"
+ "{\"movieId\":\"fytw91390391\",\"eTitle\":\"You Are the Apple of My Eye\",\"cTitle\":\"???,????????\",\"imageUrl\":\"http://test.mobibon.com.tw/MovieGoTest/Pics/pl_fytw9139039102_s.jpg\",\"releaseDate\":\"2011/8/19\",\"saleType\":\"0\"}"
+ "]}";
JSONObject jsonObj = new JSONObject(jsonData);
JSONArray movieArray = jsonObj.getJSONArray("movies");
JSONObject movieObj = null;
for (int i = 0; i < movieArray.length(); i++) {
movieObj = movieArray.optJSONObject(i);
if (null != movieObj) {
String mId = movieObj.optString("movieId");
String title = movieObj.optString("eTitle");
String cTitle = movieObj.optString("cTitle");
String imageUrl = movieObj.optString("imageUrl");
String releaseDate = movieObj.optString("releaseDate");
String saleType = movieObj.optString("saleType");
System.out.println("movieID [" + mId + "] eTitle [" + title
+ "] cTitle [" + cTitle + "] imgUrl [" + imageUrl
+ "] relDate [" + releaseDate + "] saleType ["
+ saleType + "]");
}
You can also make use of Gson, which provides you api's for Json parsing. its very easy just you need to create type of object you want.
Obviously, the top level of the json file is not a JSONArray but a JSONObject.
Use something like following:
JSONObject obj = new JSONOBject(retSrc);
JSONArray movieArray = obj.getJSONArray("movies");
//then process the movie as you did
Related
I can not retrieve all key values from JSON object retrieved from HTTP request.
This is the returned JSON object from http request:
{"data":[{"movie_id":3,"movie_name":"Promithius","genre":"a dude","year":"2016","rating":45}]}
my Android Code:
try {
//HttpJsonParser httpJsonParser = new HttpJsonParser();
JSONObject JSonObj = (JSONObject) new
JSONTokener(result).nextValue();
String mymovie = JSonObj.getString("movie_name" );
String movieGenre = JSonObj.getString("genre" );
etResponse.setText("movie=" + mymovie + " genre=" +
movieGenre);
} catch (JSONException e) {
etResponse.setText("ERROR=" + e.getMessage());
e.printStackTrace();
}
When I run it in emulator with only:
String mymovie = JSonObj.getString("movie_name" );
etResponse.setText("movie=" + mymovie;
I get back the Movie name with no error. So the issue is I can retrieve movie_name but no Genre.
Error returned says "No value for genre"
Thanks in advance.
I think the data is JSONArray.
String result = "{\"data\":[{\"movie_id\":3,\"movie_name\":\"Promithius\",\"genre\":\"a dude\",\"year\":\"2016\",\"rating\":45}]}";
try {
JSONObject JSonObj = (JSONObject) new JSONTokener(result).nextValue();
JSONArray data = JSonObj.getJSONArray("data");
for (int i=0; i<data.length(); i++){
JSONObject jsonObject = data.getJSONObject(i);
String mymovie = jsonObject.getString("movie_name" );
String movieGenre = jsonObject.getString("genre" );
String dest = "movie=" + mymovie + " genre=" + movieGenre;
Log.d(TAG, dest);
}
} catch (JSONException e) {
e.printStackTrace();
}
Below is the code that finally worked for me. I hope it can help someone else.
try{
JSONObject object = new JSONObject(result);
JSONArray Jarray = object.getJSONArray("data");
object = Jarray.getJSONObject(0);
String MovieName = object.getString("movie_name");
String Genre = object.getString("genre");
String Rating = object.getString("rating");
String Year = object.getString("year");
etResponse.setText("Movie Name = " + MovieName + " \n Genre = " +
Genre + "\n Rating = " + Rating + " \n Year = " + Year );
} catch (JSONException e) {
etResponse.setText("JSONException: " + e.getMessage());
}
Can someone show me how to write this json into a code?
Is it correct if I get this json data as json object first and the loop the jsonarray in the try catch block in android?
{"charges":[{"Fhour":"0.3","Shour":"0.2","Rhours":"0.1"}]}
Kindly help me thanks in advance
Your String can be parsed like
String json = "{\"charges\":[{\"Fhour\":\"0.3\",\"Shour\":\"0.2\",\"Rhours\":\"0.1\"}]}";
JSONObject jsonObject = new JSONObject(json);
JSONArray charges = jsonObject.getJSONArray("charges");
for (int i = 0; i < charges.length(); i++) {
JSONObject c = charges.get(i);
String fHour = c.getString("Fhour");
String sHour = c.getString("Shour");
String rHours = c.getString("Rhours");
Log.d("(f,s,r)Hours : ", "(" + fHour + "," + sHour + "," + rHours + ")");
}
Use built-in JSON library.
JSONObject buddiesDoc = new JSONObject(result);
JSONArray buddies = buddiesDoc.getJSONArray("buddies");
for (int n = 0; n < buddies.length(); n++) {
JSONObject object = buddies.getJSONObject(n);
object.getString(BuddyManager.CACHED_BUDDY_KEY_CONTACTID);
...
I am trying to parse a JSON array from a string which I receive from the server.
Example of the array is
{"data":[{"id":703,"status":0,"number":"123456","name":"Art"}]}
I am trying to parse that using the below code which is giving me Classcast Exception which shows JSonArray can not be cast to List
JSONObject o = new JSONObject(result.toString());
JSONArray slideContent = (JSONArray) o.get("data");
Iterator i = ((List<NameValuePair>) slideContent).iterator();
while (i.hasNext()) {
JSONObject slide = (JSONObject) i.next();
int title = (Integer)slide.get("id");
String Status = (String)slide.get("status");
String name = (String)slide.get("name");
String number = (String)slide.get("number");
Log.v("ONMESSAGE", title + " " + Status + " " + name + " " + number);
// System.out.println(title);
}
What should be the correct way of parsing it?
It makes sense as a JSONArray cannot be cast to a List<>, nor does it have an iterator.
JSONArray has a length() property which returns its length, and has several get(int index) methods which allow you to retrieve the element in that position.
So, considering all these, you may wish to write something like this:
JSONObject o = new JSONObject(result.toString());
JSONArray slideContent = o.getJSONArray("data");
for(int i = 0 ; i < slideContent.length() ; i++) {
int title = slideContent.getInt("id");
String Status = slideContent.getString("status");
// Get your other values here
}
you should do like this:
JSONObject o = new JSONObject(result.toString());
JSONArray array = jsonObject.getJSONArray("data");
JSONObject jtemp ;
ArrayList<MData/*a sample class to store data details*/> dataArray= new ArrayList<MData>();
MData mData;
for(int i=0;i<array.length();i++)
{
mData = new MData();
jtemp = array.getJSONObject(i); //get i record of your array
//do some thing with this like
String id = jtemp.getString("id");
mData.setId(Integer.parseInt(id));
///and other details
dataArray.put(mData);
}
and MData.class
class MData{
private int id;
/....
public void setId(int id){
this.id = id;
}
//.....
}
I am a little new to android/java. I am trying to pass JSON values into a list and then into a multidimensional array. I am not having much success.
2 questions,
1) How would I load all of the variables in a json array into children[][]?
2) How do you view children[][] in Log.i
Herei s my code:
List<String> cList = new ArrayList<String>();
String customer_name, customer_title, customer_postal_code, customer_city, customer_state, customer_street_address;
ArrayList<String> cTitle, cClubName, cPostalCode, cCity, cState, cStreet = new ArrayList<String>();
public String[][] children = null;
//... onCreate method, HTTP Connection, StringBuilder, etc. These work fine...
// Pass data into array
try{
JSONArray jArray = new JSONArray(result);
JSONObject jData=null;
String[][] children = new String[jArray.length()][6];
for(int i=0;i<jArray.length();i++){
jData = jArray.getJSONObject(i);
customer_name=jData.getString("customer_name");
Log.i("JSON ", "customer_name LOG " + customer_name);
cList.add(customer_name);
customer_title=jData.getString("event_title");
Log.i("JSON ", "customer_title LOG " + customer_title);
cList.add(customer_title);
customer_street_address=jData.getString("customer_street_address");
Log.i("JSON ", "customer_Id LOG " + customer_street_address);
cList.add(customer_street_address);
customer_city=jData.getString("customer_city");
Log.i("JSON ", "customer_city LOG " + customer_city);
cList.add(customer_city);
customer_state=jData.getString("customer_state");
Log.i("JSON ", "customer_state LOG " + customer_state);
cList.add(customer_state);
customer_postal_code=jData.getString("customer_postal_code");
Log.i("JSON ", "customer_postal_code LOG " + customer_postal_code);
cList.add(customer_postal_code);
for(int ic = 0; ic < cList.size(); ic++) {
Log.i("jData ", "length " + jData.length());
children[i][ic] = (String) cList.get(ic);
}
Log.i("Child Array", "Children array LOG " + children);
}
}catch(JSONException e1){
Toast.makeText(getBaseContext(), "No customers Found", Toast.LENGTH_LONG).show();
}catch (ParseException e1){
e1.printStackTrace();
}
}
If I understood your code correctly you don't need cList.
Something like that should do the work
String[][] children = new String[jArray.length()][6];
for(int i=0;i<jArray.length();i++){
jData = jArray.getJSONObject(i);
customer_name=jData.getString("customer_name");
Log.i("JSON ", "customer_name LOG " + customer_name);
children[i][0] = customer_name;
customer_title=jData.getString("event_title");
Log.i("JSON ", "customer_title LOG " + customer_title);
children[i][1] = event_title;
customer_street_address=jData.getString("customer_street_address");
Log.i("JSON ", "customer_Id LOG " + customer_street_address);
children[i][2] = customer_street_address;
customer_city=jData.getString("customer_city");
Log.i("JSON ", "customer_city LOG " + customer_city);
children[i][3] = customer_city;
customer_state=jData.getString("customer_state");
Log.i("JSON ", "customer_state LOG " + customer_state);
children[i][4] = customer_state;
customer_postal_code=jData.getString("customer_postal_code");
Log.i("JSON ", "customer_postal_code LOG " + customer_postal_code);
children[i][5] = customer_postal_code;
}
Make sure your JSON data is well-formed to avoid exceptions.
To view children[][] you can just iterate twice on your multidimentional array and do Log.i("MyTag", "Value: " + children[i][j]);
String[][] data = new String[jsonArray.length][];
for(int i = 0; i<jsonArray.length; i++){
data[i] = ((ArrayList)jsonArray).get(i).toArray(new String[((ArrayList)jsonArray).get(i).size])
}
for printing in log
Log.d("array", data);
I have a strange problem in my android app. In one method I do this :
try {
String r = responseBody.toString();
JSONArray jArray = new JSONArray(r);
categorys = new String[jArray.length()];
idcategory = new Integer[jArray.length()];
System.out.println("lung " + jArray.length());
for (int i = 0; i < jArray.length(); i++) {
JSONObject jsdata = jArray.getJSONObject(i);
String idcat = jsdata.getString("id_category");
idcategory[i] = Integer.valueOf(idcat);
System.out.println("Id " + idcat);
String namecategory = jsdata.getString("category_name");
categorys[i] = namecategory;
System.out.println("Category name " + namecategory);
}
and everything works fine, I get from server the categorys and category's id. In an other method I do this (for an other response) :
try {
String re = responseBody.toString();
JSONArray jArray = new JSONArray(re);
System.out.println("lung " + jArray.length());
titlephotos = new String[jArray.length()];
photolink=new String[jArray.length()];
for (int i = 0; i < jArray.length(); i++) {
JSONObject jsdata = jArray.getJSONObject(i);
String titlephoto = jsdata.getString("title");
System.out.println("titlu photo " + titlephoto);
titlephotos[i] = titlephoto;
String linkphoto=jsdata.getString("view");
System.out.println("link photo"+ linkphoto);
photolink[i]=linkphoto;
}
}catch(JSONException e) {
System.out.println("You are in catch");
}
and I get only one title photo an after that I get the message from catch(). If I don't put
String linkphoto=jsdata.getString("photo link");
System.out.println("link photo"+ linkphoto);
photolink[i]=linkphoto;
I get all the titles. I don't understand where is the problem,because the methods are similar, and the first one works fine. Can anyone help?
Thanks...
Most likely it is the space in
String linkphoto=jsdata.getString("photo link");