I'm trying to pull the "price" object from the "current" array, I have been at it for hours now with no luck, any help is appreciated! :)
try {
URL url = new URL("http://services.runescape.com/m=itemdb_rs/api/catalogue/detail.json?item=2");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line).append("\n");
}
bufferedReader.close();
return stringBuilder.toString();
} finally {
JSONArray nu1 = jobj.getJSONArray("current");
JSONObject jobj = nu1.getJSONObject(0);
String price = jobj.getString("price");
Toast.makeText(getApplicationContext(), price, Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
Log.e("ERROR", e.getMessage(), e);
return null;
}
}
protected void onPostExecute(String response) {
}
}
}
I tried to get response from your URL. here is the response :
{
"item": {
"icon": "http://services.runescape.com/m=itemdb_rs/1502782993572_obj_sprite.gif?id=2",
"icon_large": "http://services.runescape.com/m=itemdb_rs/1502782993572_obj_big.gif?id=2",
"id": 2,
"type": "Ammo",
"typeIcon": "http://www.runescape.com/img/categories/Ammo",
"name": "Cannonball",
"description": "Ammo for the Dwarf Cannon.",
"current": {
"trend": "neutral",
"price": 339
},
"today": {
"trend": "positive",
"price": "+1"
},
"members": "true",
"day30": {
"trend": "positive",
"change": "+1.0%"
},
"day90": {
"trend": "negative",
"change": "-11.0%"
},
"day180": {
"trend": "negative",
"change": "-21.0%"
}
}
}
there is no array in the response.
Edit:
assume that you store your response in a String named response, you can get price, using the following code:
JSONObject json = new JSONObject(response);
JSONObject item = json.getJSONObject("item");
JSONObject current = item.getJSONObject("current");
int price = current.getInt("price");
Edit2: use
String response = stringBuilder.toString();
and then make a JSONObject from 'response' .
Related
I can't get complete data from server by using API.
I use AsyncTask and HttpURLConnection to get data, it can work.
But when server return more data, I found that I can't get complete data.
How can I fix that, thank you.
Here is my code. and in these code, I can't get data of jsonArray_banner, it always return null array.
public class JSONTask_Login extends AsyncTask<String, String, String> {
private String deviceId, os, ver;
public JSONTask_Login(String _deviceId, String _os, String _ver) {
this.deviceId = _deviceId;
this.os = _os;
this.ver = _ver;
}
#Override
protected String doInBackground(String... params) {
try {
String SERVER_WS_URL = params[0];
parameter.clear();
parameter.put("deviceId", deviceId);
parameter.put("os", os);
parameter.put("ver", ver);
return ApiCall.postWebserviceCall(SERVER_WS_URL, parameter); // POST.
} catch (Exception e) {
return null;
}
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
if (result != null) {
JSONObject jsonObject = new JSONObject(result);
code = jsonObject.getString("code");
msg = jsonObject.getString("msg");
if (Integer.valueOf(code) == 0) {
// 1st block.
JSONObject jsonObject_userInfo = jsonObject.getJSONObject("userInfo");
....
// 2nd block.
JSONArray jsonArray_first = jsonObject.getJSONArray("anonymous_first_name");
for(int i = 0; i < jsonArray_first.length(); i++) {
JSONObject jsonObject_anonFirst = jsonArray_first.getJSONObject(i);
...
}
// 3rd block.
JSONArray jsonArray_Second = jsonObject.getJSONArray("anonymous_second_name");
for(int i = 0; i < jsonArray_Second.length(); i++) {
JSONObject jsonObject_anonSecond = jsonArray_Second.getJSONObject(i);
...
}
// 4th block.
JSONArray jsonArray_Head = jsonObject.getJSONArray("anonymous_head");
for(int i = 0; i < jsonArray_Head.length(); i++) {
JSONObject jsonObject_anonHead = jsonArray_Head.getJSONObject(i);
...
}
// 5th block.
JSONArray jsonArray_list = jsonObject.getJSONArray("posts_group_list");
for(int i = 0; i < jsonArray_list.length(); i++) {
JSONObject jsonObject_list = jsonArray_list.getJSONObject(i);
...
}
// 6th block.
// I can get data of this block, jsonArray_banner always return null array.
JSONArray jsonArray_banner = jsonObject.getJSONArray("banner_home");
for(int i = 0; i < jsonArray_banner.length(); i++) {
JSONObject jsonObject_banner = jsonArray_banner.getJSONObject(i);
...
}
}
else
return;
} else
return;
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Here is my ApiCall code:
class ApiCall {
static String postWebserviceCall(String URL, LinkedHashMap<String, String> params) {
try {
URL url = new URL(URL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000);
conn.setConnectTimeout(10000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, StandardCharsets.UTF_8));
if (params != null)
writer.write(getPostDataString(params));
writer.flush();
writer.close();
os.close();
conn.connect();
int responseCode = conn.getResponseCode();
InputStream iStream;
if (responseCode == HttpURLConnection.HTTP_OK)
iStream = conn.getInputStream();
else
iStream = conn.getErrorStream();
BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
StringBuilder response = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
response.append(line);
Log.e("test", line);
}
return response.toString();
} catch (Exception e) {
return null;
}
}
static String getWebserviceCall(String URL, LinkedHashMap<String, String> params) {
...
}
private static String getPostDataString(LinkedHashMap<String, String> params) throws UnsupportedEncodingException {
StringBuilder result = new StringBuilder();
boolean first = true;
for (Map.Entry<String, String> entry : params.entrySet()) {
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
}
return result.toString();
}
}
Here is my api structure:
{
code: 0,
msg: "",
userInfo: {
token: "token",
nick: "user",
head: "Head/Default.png",
...
},
anonymous_first_name: [
{
id: "1",
nick_name: "one",
},
{
id: "2",
nick_name: "two",
},
...
],
anonymous_second_name: [
{
id: "1",
nick_name: "one",
},
{
id: "2",
nick_name: "two",
},
...
],
anonymous_head: [
{
id: "1",
head: "System/AnonHead/star_head_01.png",
},
{
id: "2",
head: "System/AnonHead/star_head_02.png",
},
...
],
posts_group_list: [
{
post_group: "1",
title: "title",
short_title: "stitle",
icon: "System/Classify/classify_01_food.png",
img: "",
color_code: "#E53737",
},
{
post_group: "2",
title: "title",
short_title: "stitle",
icon: "System/Classify/classify_02_travel.png",
img: "",
color_code: "#3C9BA5",
},
...
],
banner_home: [
{
title: "title",
gid: "25",
url: "url",
banner: "imgurl",
start_time: "2019-08-30 00:00:00",
end_time: "2021-08-30 00:00:00",
},
{
title: "title",
gid: "24",
url: "url",
banner: "imgurl",
start_time: "2019-08-30 00:00:00",
end_time: "2021-08-30 00:00:00",
},
...
],
}
{
"page": 1,
"results": [
{
"poster_path": "/lIv1QinFqz4dlp5U4lQ6HaiskOZ.jpg",
"adult": false,
"overview": "Under the direction of a ruthless instructor, a talented young drummer begins to pursue perfection at any cost, even his humanity.",
"release_date": "2014-10-10",
"genre_ids": [
18,
10402
],
"id": 244786,
"original_title": "Whiplash",
"original_language": "en",
"title": "Whiplash",
"backdrop_path": "/6bbZ6XyvgfjhQwbplnUh1LSj1ky.jpg",
"popularity": 7.361171,
"vote_count": 1949,
"video": false,
"vote_average": 8.32
}
]
}
This is my JSON response but when i parse it the value of id is always null
Below is my networking and JSON parsing code please help..
public class movietask extends AsyncTask<String, Void, List<movieobject>> {
private String TAG;
private static final String Base_string = "http://api.themoviedb.org/3/movie/";
private static final String api_key = "388e5684ea2f3bb8de279874cb6990a5";
private static final String MOVIE_ID="id";
private static final String MOVIE_OVERVIEW="overview";
private static final String MOVIE_TITLE="original_title";
private static final String MOVIE_VOTE="vote_average";
private static final String MOVIE_POSTERPATH="poster_path";
private static final String MOVIE_RELEASE_DATE="release_date";
private static final String MOVIE_BACKDROP_PATH="backdrop_path";
// Parse json data to get arraylist of movieobjects
private List<movieobject> getparseddata(String forecastjsonstr)
throws JSONException {
final String START_OF_JSON = "results";
JSONObject startlist = new JSONObject(forecastjsonstr);
JSONArray startarray = startlist.getJSONArray(START_OF_JSON);
int noofobjects = startarray.length();
List<movieobject> objectarray = new ArrayList<>();
for (int i = 0; i < noofobjects; i++) {
JSONObject object = startarray.getJSONObject(i);
movieobject finalobjectarray = new movieobject();
finalobjectarray.setMovieId(object.getString(MOVIE_ID));
finalobjectarray.setOverview(object.getString(MOVIE_OVERVIEW));
finalobjectarray.setTitle(object.getString(MOVIE_TITLE));
finalobjectarray.setMovieRating(object.getString(MOVIE_VOTE));
finalobjectarray.setPosterPath(object.getString(MOVIE_POSTERPATH));
finalobjectarray.setReleaseDate(object.getString(MOVIE_RELEASE_DATE));
finalobjectarray.setBackdroppath(object.getString(MOVIE_BACKDROP_PATH)+"/10");
objectarray.add(finalobjectarray);
}
return objectarray;
}
protected List<movieobject> doInBackground(String... params) {
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
List<movieobject> finalobjectarray = new ArrayList<>();
// Will contain the raw JSON response as a string.
String forecastJsonStr = null;
try {
URL url = new URL(Base_string + params[0] + "?api_key="+api_key);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
// Read the input stream into a String
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
// Nothing to do.
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
return null;
}
forecastJsonStr = buffer.toString();
Log.i("hey", "Hello" + forecastJsonStr);
} catch (IOException e) {
Log.e("PlaceholderFragment", "Error ", e);
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e("PlaceholderFragment", "Error closing stream", e);
}
}
}
try {
finalobjectarray = getparseddata(forecastJsonStr);
} catch (JSONException e) {
Log.e("Json exception", e.getMessage(), e);
e.printStackTrace();
}
return finalobjectarray; //final movieobject array
}
//onPostExecute method of asynctask
protected void onPostExecute(List<movieobject> results) {
}
}
The ID is null because "id" is not a String.
Let's check your JSON.
{
"page":1,
"results":[
{
"poster_path":"/lIv1QinFqz4dlp5U4lQ6HaiskOZ.jpg",
"adult":false,
"overview":"Under the direction of a ruthless instructor, a talented young drummer begins to pursue perfection at any cost, even his humanity.",
"release_date":"2014-10-10",
"genre_ids":[
18,
10402
],
"id":244786, <------- Without "" = Integer
"original_title":"Whiplash", <-------- With "" = String
"original_language":"en",
"title":"Whiplash",
"backdrop_path":"/6bbZ6XyvgfjhQwbplnUh1LSj1ky.jpg",
"popularity":7.361171,
"vote_count":1949,
"video":false,
"vote_average":8.32
}
]
}
So, to get the value you will use getInt()
finalobjectarray.setMovieId(object.getInt(MOVIE_ID).toString());
this might help. Ideally the MovieId in your movie object should be an int:
finalobjectarray.setMovieId(""+object.getInt(MOVIE_ID));
I'm trying to read data from this API: http://events.makeable.dk/api/getEvents with the AsyncTask method which Is first time I try this. I'm trying to only read all TITLES from the API, but I'm not getting any titles.
Instead I get this exception: W/System.err: org.json.JSONException: (...)
Which shows me the whole API.
I have put Log.d(); around my code and I can se that my code never do or reach something in onPostExecute(String s) and thats is maybe why I never get any TITLES.
The many examples on the web of how to do this is so different from eachother and makes this very frustrating to solve!
private class JsonParser extends AsyncTask<String, Void, String> {
HttpURLConnection conn;
URL url = null;
#Override
protected void onPreExecute() {
super.onPreExecute();
Toast.makeText(MainActivity.this, "LOADING DATA FROM API", Toast.LENGTH_SHORT).show();
}
#Override
protected String doInBackground(String... params) {
try{
url = new URL(URL);
conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("GET");
conn.setDoOutput(true);
if(conn.getResponseCode() == HttpURLConnection.HTTP_OK){
InputStream inputStream = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine())!= null){
result.append(line);
}
return (result.toString());
}
}catch (MalformedURLException e){
e.printStackTrace();
}catch (Exception ee){
ee.printStackTrace();
}
return "";
}
#Override
protected void onPostExecute(String s) {
//------ never comes below this area //-----------
try{
JSONArray jsonArray = new JSONArray(s);
for(int i =0; i<jsonArray.length(); i++){
JSONObject jsonObject = jsonArray.getJSONObject(i);
Log.d("TAG", "JSON: " + jsonObject.getString("TITLE"));
}
}catch (Exception e){
e.printStackTrace();
}
}
}
I viewed your API's response at this Website. It is a JSON Object because it is started by an open curly brace {. So therefore use JSONObject first.
The response looks like this:
{
"success": true,
"message": "548 events returned successfully",
"last_change": 1459515263,
"events": [
{
"category": "Musik",
"category_id": "75",
"datelist": [
{
"start": 1436536800,
"end": 1436544000
}
],
"description": "",
"description_english": "",
"description_german": "",
"eventgroup": "",
"eventid": "55815f7fe714a",
"family_friendly": "0",
"last_updated": 1436166668,
"location_address": "Klostertorv 1",
"location_city": "Århus C",
"location_id": "1593",
"location_latitude": 56.158092,
"location_longitude": 10.206756,
"location_name": "Klostertorv",
"location_postcode": "8000",
"organizer_email": "",
"organizer_name": "Café Smagløs ",
"organizer_phone": "",
"picture_name": "http://www.jazzfest.dk/img/photos_big/tcha-badjo---strings-og-buttons.jpg",
"price": "-1",
"subcategory": "Musik",
"subcategory_id": "84",
"subtitle": "",
"subtitle_english": "",
"subtitle_german": "",
"tags": "Swing/Mainstream",
"tickets_url": "",
"title": "Tcha Badjo + Strings & Buttons KONCERT AFLYST",
"title_english": "Tcha Badjo + Strings & Buttons CONCERT CANCELLED",
"title_german": "Tcha Badjo + Strings & Buttons CONCERT CANCELLED",
"url": "http://www.jazzfest.dk/?a=reviews&lang=&kryds_id=2122&y=2015",
"user_id": "23",
"video_url": ""
}]
}
So therefore it is:
try {
JSONObject object = new JSONObject(s);
JSONArray events = object.getJSONArray("events");
int evSize = events.length();
for (int x = 0; x < evSize; x++) {
JSONObject object1 = events.getJSONObject(x);
String title = object1.getString("title");
}
} catch (JSONException e) {
e.printStackTrace();
}
In api response sometimes It can be array, sometimes it can be string.
Here details is Array
{ "ts": "2015-06-16 11:28:33","success": true,"error": false,"details": [
{
"user_id": "563",
"firstname": "K.Mathan"
},
{
"user_id": "566",
"firstname": "Surya"
},
{
"user_id": "562",
"firstname": "Idaya"
} ]}
Sometimes details can be string
{ "ts": "2015-06-16 11:28:33",
"success": true,
"error": false,
"details": "no data" }
Here details is String
How to get value from this type of response
My current declaration is
#SerializedName(value="details")
public List<detailslist> details ;
Anyone please help me to find the solution?
Did you try with the raw response type?
#GET("your_url")
void getDetails(Callback<Response> cb);
Then you can parse the Response using JSONObject and JSONArray like this:
Callback<Response> callback = new Callback<Response>() {
#Override
public void success(Response detailsResponse, Response response2) {
String detailsString = getStringFromRetrofitResponse(detailsResponse);
try {
JSONObject object = new JSONObject(detailsString);
//In here you can check if the "details" key returns a JSONArray or a String
} catch (JSONException e) {
}
}
#Override
public void failure(RetrofitError error) {
});
Where the getStringFromRetrofitRespone could be:
public static String getStringFromRetrofitResponse(Response response) {
//Try to get response body
BufferedReader reader = null;
StringBuilder sb = new StringBuilder();
try {
reader = new BufferedReader(new InputStreamReader(response.getBody().in()));
String line;
try {
while ((line = reader.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
return sb.toString();
}
I guess you can write your own deserializer to use in retrofit but it also works with just inferring that it's an object and then handle it later in your code.
#SerializedName(value="details")
public Object details;
I spent the past 4 hours looking at various answers and other resources but I simply can't wrap my head around JSON parsing. I need some help.
Here is the JSON string:
{
"success": true,
"categories": [
{
"category_id": "20",
"parent_id": "0",
"name": "Desktops",
"image": "***",
"href": "***",
"categories": null
},
{
"category_id": "25",
"parent_id": "0",
"name": "Components",
"image": "***",
"href": "***",
"categories": null
},
{
"category_id": "34",
"parent_id": "0",
"name": "MP3 Players",
"image": "***",
"href": "***",
"categories": null
}
]
}
Here is my Data class:
public class Data
{
String success;
List<Category> categories;
// Various get/set functions and a toString override
public class Category
{
String category_id;
String name;
String image;
// Various get/set functions
}
}
Here is where I'm trying to read this:
private class GetJson extends AsyncTask<String, Void, String>
{
#Override
protected String doInBackground(String... params)
{
String results = "Fail";
URL url = null;
try
{
url = new URL("***");
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
URLConnection ucon = null;
try
{
ucon = url.openConnection();
InputStream is = ucon.getInputStream();
BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(is));
String line = "";
String result = "";
while((line = bufferedReader.readLine()) != null)
{
result += line;
}
Data data = new Gson().fromJson(result, Data.class);
result = data.toString();
}
catch (IOException e)
{
e.printStackTrace();
}
return results;
}
protected void onPostExecute(String result)
{
Toast.makeText(con, result, Toast.LENGTH_SHORT);
}
}
I'm not getting anything on the stacktrace at all. I checked ADB several times. Everything seems to be working but I get no Toast or error message.
What am I doing wrong?
you forgot to show your Toast
try this
Toast.makeText(con, result, Toast.LENGTH_SHORT).show();
lol
and further
Data data = new Gson().fromJson(result, Data.class);
result = data.toString();
return result; // need return this
otherwise will always get "Fail"
//First generate getter setter of data class variables.
TypeToken<Data> tokenPoint1 = new TypeToken<Data>() {};
//SYSO result string here for Confirmation
Gson gson = new Gson();
Data dataobj= gson.fromJson(result, tokenPoint1.getType());
// syso dataobj.getname();
//Hope this will work for you