android-parsing nested json Objects - android

i have to implement json data in my application. but i can't get it how to fetch data from server. i am using ION library.
{
"search": [{
"id": "5454003",
"description": "Larger Than Life",
"url": "http://audiojungle.net/item/larger-than-life/5454003",
"type": "item",
"sales": "1469",
"rating": "5",
"item_info": {
"id": "5454003",
"item": "Larger Than Life",
"url": "http://audiojungle.net/item/larger-than-life/5454003",
"user": "pinkzebra",
"thumbnail": "https://0.s3.envato.com/files/67162834/upbeatsongwinner2.jpg",
"sales": "1469",
"rating": "5",
"rating_decimal": "4.96",
"cost": "18.00",
"preview_type": "audio",
"preview_url": "https://0.s3.envato.com/files/94250640/preview.mp3",
"length": "2:35"
}
} ] }
this is my json data. i want to display in my application data like "cost" , "user" ect. but i didn't get it. ion code is here,
Ion.with(this)
.load("http://marketplace.envato.com/api/edge/search:audiojungle,,happy.json")
.asJsonObject().setCallback(new FutureCallback<JsonObject>() {
#Override
public void onCompleted(Exception arg0, JsonObject data) {
// TODO Auto-generated method stub
}
});
so if anybody knows then please help me. thank you in advance.

EDIT: The first info that you posted was has some misleading information, i checked the answer that you posted and i have a working code for you,
code:
Ion.with(this)
.load("http://marketplace.envato.com/api/edge/search:audiojungle,,happy.json")
.asString().setCallback(new FutureCallback<String>() {
#Override
public void onCompleted(Exception e, String result) {
try {
parseJson(new JSONObject(result));
} catch (JSONException e1) {
e1.printStackTrace();
}
}
});
To parse the response data:
private void parseJson(JSONObject result) {
try {
JSONArray jsonArray = result.getJSONArray("search");
for(int a=0;a<jsonArray.length();a++){
System.out.println(jsonArray.getJSONObject(a).getString("id"));
System.out.println(jsonArray.getJSONObject(a).getString("description"));
System.out.println(jsonArray.getJSONObject(a).getString("url"));
System.out.println(jsonArray.getJSONObject(a).getString("type"));
System.out.println(jsonArray.getJSONObject(a).getString("sales"));
System.out.println(jsonArray.getJSONObject(a).getString("rating"));
// JSON data with in JSONObject "item_info"
System.out.println(jsonArray.getJSONObject(a).getJSONObject("item_info").getString("id"));
System.out.println(jsonArray.getJSONObject(a).getJSONObject("item_info").getString("item"));
System.out.println(jsonArray.getJSONObject(a).getJSONObject("item_info").getString("url"));
System.out.println(jsonArray.getJSONObject(a).getJSONObject("item_info").getString("user"));
System.out.println(jsonArray.getJSONObject(a).getJSONObject("item_info").getString("thumbnail"));
System.out.println(jsonArray.getJSONObject(a).getJSONObject("item_info").getString("sales"));
System.out.println(jsonArray.getJSONObject(a).getJSONObject("item_info").getString("rating"));
System.out.println(jsonArray.getJSONObject(a).getJSONObject("item_info").getString("rating_decimal"));
System.out.println(jsonArray.getJSONObject(a).getJSONObject("item_info").getString("cost"));
System.out.println(jsonArray.getJSONObject(a).getJSONObject("item_info").getString("preview_type"));
System.out.println(jsonArray.getJSONObject(a).getJSONObject("item_info").getString("preview_url"));
System.out.println(jsonArray.getJSONObject(a).getJSONObject("item_info").getString("length"));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
Remember to use JSONArray(org.json.JSONArray) and JSONObject(org.json.JSONObject) form the org.json libary not JsonArray(com.google.gson.JsonArray;) or JsonObject(com.google.gson.JsonObject) from the com.google.gson library, it get things mess up;
To make things easy paste response here http://json.parser.online.fr/ to see which one is a jsonobject or array

Process :
JsonArray searchArray = getJsonArray("search");
JsonObject index_0_Object= searchArray.getJsonObject("index_0");
JsonObject infoObject = index_0_Object.getJsonObject("item_info");
String id = infoObject.getString("id");
System.out.pritnln(id);
Edited :
first : you have to find "search" array , after it use indexing to get its object , so now you have JsonObject , from it get "item_info" object , from there you can find "id" object .

> yes i got it...
Ion.with(this)
.load("http://marketplace.envato.com/api/edge/search:audiojungle,,happy.json")
.asString().setCallback(new FutureCallback<String>() {
#Override
public void onCompleted(Exception arg0, String data) {
// TODO Auto-generated method stub
try {
JSONObject jObject = new JSONObject(data);
JSONArray jArray = jObject.getJSONArray("search");
for ( int i = 0 ; i < jArray.size() ; i++ )
{
JSONObject jObject_0 = jArray.getJSONObject(i);
JSONObject jObj = jObject_0.getJSONObject("id");
Log.e("id : ",id+"");
}
//JSONObject jObject_0 = jArray.getJSONObject(1);
//JSONObject jObj = jObject_0.getJSONObject("item_info");
//cost.setText(jObj.getString("cost"));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
> but this returns only one value. i want to multiple value according to array list.
check your logs .

Related

How do I parse json key value pairs inside a json object using Volley Android

How do I parse this using Volley
{
"ref": "suc",
"contactInfo": {
"name": "Jezzi",
"age": "3",
"Place": "Kochi"
}
}
Code in Android
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
String ref = jsonObject.getString("ref");
} catch (Exception e ) {
Log.i("Hello", e.toString);
}
}
I'm getting string value ref, but I don't know how to get the other values.
I think this might help you:
try {
JSONObject jsonObject = new JSONObject(response);
String ref = jsonObject.getString("ref");
JSONObject contactJsonObject = jsonObject.getJSONObject("contactInfo");
String name = contactJsonObject.getString("name");
// and other values like this
} catch (Exception e ) {
Log.i("Hello", e.toString);
}

my API does not show me anything and without error?

I'm working on a web service application, I display the data in a listview
At the beginning everything works but when I changed my api nothing is displayed and no error appears , I did not find the problem please !! how can I display my data !!
it's the part of the code !!
private class GetHttpResponse extends AsyncTask<String, Void,
ArrayList<subjects>>
{
public Context context;
String ResultHolder;
public GetHttpResponse(Context context)
{
this.context = context;
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
}
#Override
protected ArrayList<subjects> doInBackground(String... arg0)
{
HttpServicesClass httpServiceObject = new HttpServicesClass(arg0[0]);
ArrayList<subjects> subjectsList = new ArrayList<subjects>();
try
{
httpServiceObject.ExecutePostRequest();
if(httpServiceObject.getResponseCode() == 200)
{
ResultHolder = httpServiceObject.getResponse();
if(ResultHolder != null)
{
JSONArray jsonArray = null;
try {
jsonArray = new JSONArray(ResultHolder);
JSONObject jsonObject;
subjects subjects;
for(int i=0; i<jsonArray.length(); i++)
{
subjects = new subjects();
jsonObject = jsonArray.getJSONObject(i);
if(valueInteger == jsonObject.getInt("tache_id") )
{
// subjects.nom=jsonObject.getString("nom");
subjects.SubjectName =
jsonObject.getDouble("tarif");
subjects.technicien_id =
jsonObject.getString("technicien_id");
subjectsList.add(subjects);
}}}
catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}}}}
catch (Exception e)
{
// TODO Auto-generated catch block
Log.e("Tech", "exception", e);
}
return subjectsList;
}
and this is my json
[
{
"tache_id": "2",
"technicien_id": "2",
"tarif": "100"
},
{
"tache_id": "3",
"technicien_id": "3",
"tarif": "200"
}]
Most probably there is an exception but your are catching it.Start removing your catch statements one by one until you find the error or put log messages in the catch statements.
When you changed your Api your response structure may be changed.So, Ensure the following steps:
Step1 - Save the response of your Api
Step2 - Your Api's JSON response contain Arrays and Objects.Write your code according to the response.

Android : Sorting of JSON Data obtained or taken by making rest call

My question is that i have to display my data which is fetched from JSON file ,the json file is below. But i want the data to be in sorted form after getting from JSON file i.e after the rest call when data is obtained from controller in viewmodel,so that i can directly display it on the View Class. which has cardviews.
{
"employeeList":[
{
"employeeName": "aaaa",
"employeeStatus": "Trainee",
"company": "IBM",
"mobile": "894996662"
},
{
"employeeName": "bbbb",
"employeeStatus": "Fellowship",
"company": "Wipro",
"mobile": "9876000021"
},
{
"employeeName": "cccc",
"employeeStatus": "Fellowship",
"company": "CGI",
"mobile": "9876000021"
},
{
"employeeName": "cccc",
"employeeStatus": "Fellowship",
"company": "CGI",
"mobile": "9876000021"
}
]
}
And the .java file is below,were i have not done the sorting.I need the help,Thank you.
try {
//As the data in rest call contained in JSONObject inside that JSONArray and inside
//JSONArray JSONObject is there ,Hence to get the data and set to the Model Class
//Creating JSON Object and obtained the data in bytes
JSONObject jsonObject = new JSONObject(new String(bytes));
Log.i("json object", "employeeList: ");
if (jsonObject != null) {
JSONArray jsonArray = jsonObject.getJSONArray("employeeList");
Log.i("json Array", "employeeList: " + jsonArray.length());
//Creating the object of modelClass
if (jsonArray.length() != 0) {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject childObject = jsonArray.getJSONObject(i);
//Through the object of model Class the obtained data is set to the
//Model class
EnggFragModel enggFragModel = new EnggFragModel();
enggFragModel.setImageurl(childObject.getString("imageUrl"));
Log.i("image", "employeeData: "+childObject.getString("imageUrl"));
enggFragModel.setEmployeeName(childObject.getString("employeeName"));
enggFragModel.setEmployeeStatus(childObject.getString("employeeStatus"));
enggFragModel.setCompany(childObject.getString("company"));
enggFragModel.setEmployeeMobile(childObject.getString("mobile"));
enggFragModel.setEmployeeEmail(childObject.getString("emailId"));
enggFragModel.setEngineerID(childObject.getString("engineerId"));
Log.i("EngineerId", "employeeData: " + childObject.getString("engineerId"));
enggArrayList.add(enggFragModel);
}
enggViewModelInterface.enggViewMInterface(enggArrayList);
Log.i("Employee", "employeeList: " + enggArrayList);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
Log.i("Employee", "employeeList: ");
The solution is to take JSONArray "employeeList" convert it to ArrayList of JSONObject and sort it, using Collections.
ArrayList<JSONObject> array = new ArrayList<JSONObject>();
JSONArray jsonArray = new JSONArray();
for (int i = 0; i < jsonArray.length(); i++) {
try {
array.add(jsonArray.getJSONObject(i));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Collections.sort(array, new Comparator<JSONObject>() {
#Override
public int compare(JSONObject lhs, JSONObject rhs) {
// TODO Auto-generated method stub
try {
return (lhs.getString("Name").toLowerCase().compareTo(rhs.getString("Name").toLowerCase()));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return 0;
}
}
});
Here is original

How to sort an JsonObject of Multiple Jsonobjects inside android

I am working on an android application and in some of my code I want to sort a JsonObject according to some value inside it in Descending order.
"smileys": {
"2": {
"image_icon": "http://devaddons1.socialengineaddons.com/mobiledemotesting/public/system/a2/39/01/1376a_0d1e.png?c=4a00",
"id": 2,
"count": 1
},
"3": {
"image_icon": "http://devaddons1.socialengineaddons.com/mobiledemotesting/public/system/a4/39/01/1376c_35c0.png?c=59a3",
"id": 3,
"count": 2
},
"4": {
"image_icon": "http://devaddons1.socialengineaddons.com/mobiledemotesting/public/system/a6/39/01/1376e_2019.png?c=f190",
"id": 4,
"count": 1
}
},
I want to sort this JsonObject based on the key value "count", so that the JsonObject with higher count will come first and so on.
I have already tried it using the below code
ArrayList<JSONObject> array = new ArrayList<>();
JSONArray smileyKeys = smileyArrays.names();
for (int i = 0; i < smileyArrays.length(); i++) {
try {
array.add(smileyArrays.getJSONObject(smileyKeys.optString(i)));
} catch (JSONException e) {
e.printStackTrace();
}
}
Collections.sort(array, new Comparator<JSONObject>() {
#Override
public int compare(JSONObject lhs, JSONObject rhs) {
// TODO Auto-generated method stub
try {
if(lhs.optInt("count") < rhs.getInt("count") ){
return 1;
} else {
return -1;
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return 0;
}
}
});
JSONArray jsonArray = new JSONArray(array);
JsonObject smileysSortedAdday = jsonArray.optJSONObject(0);
But it is not working with JsonObject and I cannot convert it in JsonArray. Can someone please guide me how can I achieve this.
Thanks a lot in advanced.

Android parse json force stopped

I am parsing a json url: http://www.json-generator.com/api/json/get/bQmwsOmYeq?indent=2 but I failed to make it happen. I am getting an error. What's wrong with this code?
public void parseJsonResponse(String result) {
Log.i(TAG, result);
pageCount++;
try {
JSONObject json = new JSONObject(result);
JSONArray jArray = json.getJSONArray("name");
for (int i = 0; i < jArray.length(); i++) {
JSONObject jObject = jArray.getJSONObject(i);
CountryInfor country = new CountryInfor();
country.setId(jObject.getString("id"));
country.setName(jObject.getString("name"));
countries.add(country);
}
adapter.notifyDataSetChanged();
if (dialog != null) {
dialog.dismiss();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
Replace
JSONObject json = new JSONObject(result);
JSONArray jArray = json.getJSONArray("name");
these two lines by
JSONArray jArray = new JSONArray(result);
Also change
country.setId(jObject.getString("id"));
by
country.setId(jObject.getInt("id") + "");
Because id is of type int not a String.
And it will work fine.
You are getting response like
[
{
"id": ​1,
"name": "Vietnam"
},
{
"id": ​2,
"name": "China"
},
{
"id": ​3,
"name": "USA"
},
{
"id": ​4,
"name": "England"
},
{
"id": ​10,
"name": "Russia"
}
]
So the response is JSONArray and not JSONObject.
Hope it'll help.
Edit
#Override
protected String doInBackground(Void... params) {
// call load JSON from url method
if(loadJSON(this.url) != null) {
return loadJSON(this.url).toString();
}
Log.d("LoadJSONFromUrl", "Failed to get JSONObject.");
return null;
}
You are getting JSONObject null, so the error is.
- You should know what is NullPointerException
the issue is with this line
JSONArray jArray = json.getJSONArray("name");
There is no array with name name. it is failing here. Correct this part to obtain the array properly. Rest looks fine.

Categories

Resources