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;
Related
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);
}
Im sorry for asking such a simple question, im struggling to get the values in JSONArray in the JSONArray without the variables inside the Array. Im using Retrofit library in android studio.Give me link or hint to get the value, please help. TQ in advance.
And here is the JSON format:
{
"meta":{
"code":200
},
"response":{
"provider":"jakim",
"code":"wlp-0",
"origin":"wlp-0",
"jakim":"sgr03",
"source":"http:\/\/www.e-solat.gov.my\/web\/muatturun.php?zone=sgr03&year=2018&bulan=7&jenis=year&lang=my&url=http:\/\/mpt.i906.my",
"place":"Kuala Lumpur",
"times":[
[
1531691280,
1531696200,
1531718520,
1531730760,
1531740600,
1531745100
],
[ ],
[ ],
[ ],
[ ],
[ ],
[ ]
]
}
}
or can view the link for json: json link here
Here is my code:
private void getPrayTimeMalay(String code, String filter) {
ApiServiceInterface apiEndPoint = Utility.getRetrofitInstanceMalay().create(ApiServiceInterface.class);
Call<ResponseBody> call = apiEndPoint.getPrayerTimeMalay(code, filter);
call.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
try {
String tmp = response.body().string();
JSONObject jsonData = new JSONObject(tmp);
Log.d("getPrayer", "onResponse: " + jsonData);
JSONObject jsonMeta = jsonData.getJSONObject("meta");
JSONObject jsonResponse = jsonMeta.getJSONObject("response");
if (jsonMeta.getInt("code") == 200) {
PrayerTime prayerTime = new PrayerTime();
prayerTime.code = jsonResponse.getString("code");
prayerTime.origin = jsonResponse.getString("origin");
prayerTime.place = jsonResponse.getString("place");
JSONArray jsonTime = new JSONArray("times");
for (int i = 0; i <= jsonTime.length(); i++) {
}
}
} catch (Throwable e) {
e.printStackTrace();
}
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
}
});
}
try this way
JSONArray jsonTime = jsonResponse.getJSONArray("times");
** EDIT **
try {
String st= (String) jsonTime.get(0);
mTextview.setText(st); //set the first item in array to textview
} catch (JSONException e) {
e.printStackTrace();
}
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' .
I am getting problem to parse json in android spinner. I have tried by below listed code but I am getting full json array in spinner like screenshot
My Json Array
{"Department":[{"1":"Computer"},{"2":"IT"},{"3":"Civil"}]} // like this type json string
My Code
public class GetDropdownItems extends AsyncTask<Void, Void, String[]> {
public GetDropdownItems() {
super();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
Log.i("MY_NETWORK", "first");
}
#Override
protected String[] doInBackground(Void... params) {
StringBuilder sbstaffdep = new StringBuilder();
String staffdepURL = StaticDataEntity.URL_GETDEP;
String charset = "UTF-8"; // Or in Java 7 and later, use the constant: java.nio.charset.StandardCharsets.UTF_8.name()
URLConnection connectionstaffDep = null;
try {
connectionstaffDep = new URL(staffdepURL).openConnection();
} catch (IOException e) {
e.printStackTrace();
}
connectionstaffDep.setDoOutput(true); // Triggers POST.
connectionstaffDep.setRequestProperty("Accept-Charset", charset);
connectionstaffDep.setConnectTimeout(6000);
InputStream responsestaffDep = null;
try {
responsestaffDep = connectionstaffDep.getInputStream();
} catch (IOException e) {
e.printStackTrace
();
return new String[]{"unreachable"};
}
BufferedReader brstaffDep = new BufferedReader(new InputStreamReader(responsestaffDep));
String readstaffDep;
try {
while ((readstaffDep = brstaffDep.readLine()) != null) {
//System.out.println(read);
sbstaffdep.append(readstaffDep);
}
} catch (IOException e) {
e.printStackTrace();
}
try {
brstaffDep.close();
} catch (IOException e) {
e.printStackTrace();
}
String[] finaldata = new String[1];
finaldata[0] = sbstaffdep.toString();
return finaldata;
}
#Override
protected void onPostExecute(String[] s) {
super.onPostExecute(s);
if (s[0].equals("unreachable")) {
new SweetAlertDialog(SignUpStaff.this, SweetAlertDialog.ERROR_TYPE)
.setTitleText("Oops...")
.setContentText("Unable to connect to server ! \n Please try again later.")
.setCancelText("Ok")
.setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
#Override
public void onClick(SweetAlertDialog sweetAlertDialog) {
sweetAlertDialog.cancel();
}
})
.show();
return;
}
Log.i("MY_NETWORK", s.toString());
String[] dataofdropdowndep = s[0].split(",");
ArrayAdapter<String> adapterdep = new ArrayAdapter<String>(SignUpStaff.this, android.R.layout.simple_list_item_1, dataofdropdowndep);
adapterdep.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
dropstaffdep.setAdapter(adapterdep);
}
}
public class GetDropdownItems extends AsyncTask<Void, Void, String> {
public GetDropdownItems() {
super();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
Log.i("MY_NETWORK", "first");
}
#Override
protected String doInBackground(Void... params) {
StringBuilder sbstaffdep = new StringBuilder();
String staffdepURL = StaticDataEntity.URL_GETDEP;
String charset = "UTF-8"; // Or in Java 7 and later, use the constant: java.nio.charset.StandardCharsets.UTF_8.name()
URLConnection connectionstaffDep = null;
try {
connectionstaffDep = new URL(staffdepURL).openConnection();
} catch (IOException e) {
e.printStackTrace();
}
connectionstaffDep.setDoOutput(true); // Triggers POST.
connectionstaffDep.setRequestProperty("Accept-Charset", charset);
connectionstaffDep.setConnectTimeout(6000);
InputStream responsestaffDep = null;
try {
responsestaffDep = connectionstaffDep.getInputStream();
} catch (IOException e) {
e.printStackTrace
();
return "unreachable";
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
responsestaffDep, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
Log.d("-------------", json);
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
return json;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
if (s.equals("unreachable")) {
new SweetAlertDialog(SignUpStaff.this, SweetAlertDialog.ERROR_TYPE)
.setTitleText("Oops...")
.setContentText("Unable to connect to server ! \n Please try again later.")
.setCancelText("Ok")
.setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
#Override
public void onClick(SweetAlertDialog sweetAlertDialog) {
sweetAlertDialog.cancel();
}
})
.show();
return;
}
Log.i("MY_NETWORK", s.toString());
Json js=new Json(s);
JSONArray array=js.getJSONArray("Department");
for(JSONArray b:array){
// traverse array here
}
ArrayAdapter<String> adapterdep = new ArrayAdapter<String>(SignUpStaff.this, android.R.layout.simple_list_item_1, dataofdropdowndep);
adapterdep.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
dropstaffdep.setAdapter(adapterdep);
}
}
HI Change your Json Response from server or you can change manually .
Here is your format :
{"Department"
[
{
"1": "Computer"
},
{
"2": "IT"
},
{
"3": "Civil"
}
]
}
Please check it with any json viewer format online.
this type json data:
check this json array:
{
"schools": [{
"Name": "Hill View Elementary",
"SchoolID": "HVE"
}, {
"Name": "Mill View",
"SchoolID": "MVE"
}, {
"Name": "Big School",
"SchoolID": "BSC"
}]
}
your mistake is you are not putting comma between two objects
The way you are fetching the Json file is wrong, there is already Json classes that can easly get each array,object or key alone.
org.json is the library we are going to use with the JSONArray and JSONObject classes.
Before we start you should know a basic understanding of the Json file scheme :
"name":{} this is the array syntax represented by the {} symbols, this array can hold arrays,objects or keys.
[] represent and object which can hold arrays and keys too but it doesn't have name.
"key":"value" now the is key type which can hold the data or values you want and has a key to retrieve it by name.
Now here is a piece of code to fetch your file and get each part of the Json file alone and then you can populate it as you wish.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.res.Resources;
public class Fetch {
final private static String DEPARTMENT = "Department";
String [] departments ;
public void fetch(Resources r , int resourceID) {
String JsonString = readStringFromRaw(r, resourceID);
//the whole josn file is a json object even if it starts with { and ends with } so...
try {
JSONObject mainObject = new JSONObject(JsonString);
// the JSONObject throws a JSONException if there is something wrong with the syntax
JSONArray department = mainObject.getJSONArray(DEPARTMENT);
int length = department.length();
departments = new String[length];
JSONObject object;
for(int i = 0 ; i < length ; i++){
object = department.getJSONObject(i);
departments[0] = object.getString(""+i+1);
//this because you tagged the keys with 1 , 2 , 3 and so on.. so it has the value of the object that it is in + 1 .
//the reason I put "" empty quotations is because I want it a string so this is a way to cast the numbers to strings .
}
} catch (JSONException e) {
e.printStackTrace();
}
}
public static String readStringFromRaw(Resources r, int resourceID) {
InputStream is = r.openRawResource(resourceID);
BufferedReader br = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder(1000);
String line;
try {
while ((line = br.readLine()) != null)
sb.append(line);
br.close();
is.close();
return sb.toString();
} catch (IOException e) {
return e.getMessage();
}
}
}
With this class you can get a String array holding the departments you want for your json file that you have.
The heirarchy between arrays and objects is very important so keep in mind that when you write a json file make it less complicated to extract the information easier.
I got this app that requires four places on screen to be up-to-date (title, address, date and image source).
So, I thought that maybe I could just makeup four different JSON files that app will read and if I would like to change what app is showing I would just change those JSON files that I'd have on my server.
Maybe something like this (file.json):
{"app": {
"title": "Screen no. 1",
"address": "Sesame Street",
"date": "01-01-2014",
"image": "http://myserver.com/image.jpg"
}}
and in Android app source of course there would be JSONParser that will get informations from "http://myserver.com/file.json". What do You think - would be that good enough or is there any better (and easier) solution? I tried to get to know Google Endpoints, but it's really cumbersome.
edit1: I got to this point where I use JSONParser custom class from here: How to parse JSON in Android
In debug mode I found values from file.json to be downloaded so I have to read it somehow now - it prints "Got the address: " but without value:
Thread thread = new Thread(new Runnable(){
#Override
public void run() {
try {
Log.i("ABCDE", "Start Thread");
//JSON
JSONParser jparser = new JSONParser();
JSONObject data = jparser.getJSONFromUrl("http://myserv.com/file.json");
Log.i("AbCDE", "Afer getting JSON");
//JSONObject data = new JSONObject(myDataJson);
String address = "";
try {
address = data.getString("address");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.i("ABCDE", "Got the address: " + address);
} catch (Exception e) {
e.printStackTrace();
}
}
});
edit2: my XML suddenly stopped working (it validates and makes hierarchy tree well, but not every time):
{
"party1": {
"title": "Screen no. 1",
"address": "Sesame Street",
"date": "01-01-2014",
"image": "http://myserver.com/image.jpg",
"destination": "somewhere"
},
"party2": {
"title": "Screen no. 2",
"address": "Oak Street",
"date": "01-01-2014",
"image": "http://myserver.com/image.jpg",
"destination": "somewhere"
},
"party3": {
"title": "Screen no. 1",
"address": "Sesame Street",
"date": "01-01-2014",
"image": "http://myserver.com/image.jpg",
"destination": "somewhere"
},
"party4": {
"title": "Screen no. 1",
"address": "Sesame Street",
"date": "01-01-2014",
"image": "http://myserver.com/image.jpg",
"destination": "somewhere"
}
}
JSON validators says that it's okay or SyntaxError: unexpected token.
This is my JSONParser.java class:
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
Yes, obtaining data from your server as a JSON file seems to be the best and most lighweight way of solving this (although you provided little data on what the data should actually mean).
I would suggest using org.json library, as it will allow you to do something like this, cutting time on the parsing:
String myDataJson = ... /* Obtain the data here */
long lastChangeTimestamp = ... /* Obtain the last saved timestamp, probably from SharedPrefs */
JSONObject data = new JSOBObject(myDataJson);
long newTimestamp = data.getLong("ts");
if(newTimestamp > lastChangeTimestamp){
String title = data.getString("title");
String address = data.getString("address");
String date = data.getString("date");
String image = data.getString("image");
/* Do somtehing with the newly obtained data and save the new timestamp to SharedPrefs */
}
Well, I have a very nice idea, i would suggest using the Gson library.
available from here, with perfect tutorial here
With Gson library you can simply convert JSON To/From java object !
Try to create class with name: app:
app.java:
public class app {
public String title;
public String address;
public String date;
public String image;
public app() {
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
}
Then try to use the Gson library, it will get the json file than using the .fromJSON function it will return an instance of app.java
I hope it will help you, best regards.