How to get the JSONArray without variables? - android

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();
}

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);
}

How to get an specific element in JSON?

If I have a JSON like below:
{
"Division": [
{
"DivisionId": 1,
"DivisionName" : "A"
},
{
"DivisionId": 2,
"DivisionName" : "B"
}
],
"Title": [
{
"TitleId": 11,
"Title": "Title 1"
},
{
"TitleId": 12,
"Title": "Title 2"
}
]
}
How can I get the Division only with its values inside? What I'm trying to achieve is to put the values of Division inside my ArrayList. I'm using Volley to get the JSON result and what I tried is on the onResponse I used JSONArray divisionArr = response.getJSONArray("Division"); and loop it here's my code
JSONArray divisionArr = response.getJSONArray("Division");
for (int i = 0; i < divisionArr.length(); i++) {
Division division = new Division();
JSONObject divisionObj = (JSONObject) divisionArr.get(i);
division.setId(divisionObj.getInt("DivisionId"));
division.setName(divisionObj.getString("DivisionName"));
divisionArrayList.add(division);
}
But I'm having an error ParseError, I maybe doing it wrong, but I don't know what is it. Please help, thank you.
///////
Here's my Volley request
public void getData(Response.Listener<JSONObject> listener, Response.ErrorListener errorListener) {
try{
String syncCall = Constants.VOLLEY;
request = new JsonObjectRequest(Method.GET,
syncCall,
null,
listener,
errorListener);
request.setRetryPolicy(
new DefaultRetryPolicy(
60000,//DefaultRetryPolicy.DEFAULT_TIMEOUT_MS, // 2500
1,//DefaultRetryPolicy.DEFAULT_MAX_RETRIES, // 1
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT)); //1f
mRequestQueue.add(request);
} catch (Exception e) {
e.printStackTrace();
}
}
Then in my Activity
private void callSyncVolley() {
final ProgressDialog pd = new ProgressDialog(this);
pd.setMessage("Fetching data....");
pd.show();
Response.Listener<JSONObject> listener = new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray divisionArr = response.getJSONArray("Division");
for (int i = 0; i < divisionArr.length(); i++) {
Division division = new Division();
JSONObject divisionObj = (JSONObject) divisionArr.get(i);
division.setId(divisionObj.getInt("DivisionId"));
division.setName(divisionObj.getString("DivisionName"));
divisionArrayList.add(division);
}
pd.dismiss();
} catch (JSONException e) {
e.printStackTrace();
Log.e(TAG, "Error: " + e.getMessage());
pd.dismiss();
}
}
};
Response.ErrorListener errorListener = new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if (error.networkResponse != null) {
Log.d(TAG, "Error Response code: " + error.networkResponse.statusCode);
pd.dismiss();
}
if (error instanceof TimeoutError || error instanceof NoConnectionError) {
Log.d(TAG, "Error Response code: Timeout/NoConnection");
pd.dismiss();
} else if (error instanceof AuthFailureError) {
//TODO
Log.d(TAG, "Error Response code: AuthFailureError");
pd.dismiss();
} else if (error instanceof ServerError) {
//TODO
Log.d(TAG, "Error Response code: ServerError");
pd.dismiss();
} else if (error instanceof NetworkError) {
//TODO
Log.d(TAG, "Error Response code: NetworkError");
pd.dismiss();
} else if (error instanceof ParseError) {
//TODO
Log.d(TAG, "Error Response code: ParseError");
pd.dismiss();
}
}
};
VolleyRequestManager.getInstance().doRequest().getData(listener, errorListener);
}
The error only shows Error Response code: ParseError
Your JSON format is invalid,
{
"Division": [
{
"DivisionId": 1,
"DivisionName" : A
},
{
"DivisionId": 2,
"DivisionName" : B
}
],
"Title": [
{
"TitleId": 11,
"Title": "Title 1"
},
{
"TitleId": 12,
"Title": "Title 2"
}
],
}
I just pasted your format here
divisionArr.setName(divisionObj.getString("DivisionName")); &&
You are trying to access a String which is not wrapped in double quotes,the String A and String B is not wrapped in double quotes.
Unnecessary comma at the end of the array ],
You can try like this, If you try to get using opt it will get value or null, so you can check that produced further
get and opt type
Use getType() to retrieve a mandatory value. This fails with a JSONException if the requested name has no value or if the value
cannot be coerced to the requested type.
Use optType() to retrieve an optional value. This returns a system- or user-supplied default if the requested name has no value or if the
value cannot be coerced to the requested type.
Example:
getJSONArray - Returns the value mapped by name if it exists and is a JSONArray, or throws otherwise., so we can't handle the upcoming line of code it will go to try block,
But optJSONArray - Returns the value mapped by name if it exists and is a JSONArray, or null otherwise., so using that null value we can handle the code easily
try {
JSONArray divisionArr = response.optJSONArray("Division");
if(divisionArr != null) {
for (int i = 0; i < divisionArr.length(); i++) {
Division divisoin = new Division();
JSONObject divisionObj =divisionArr.optJSONObject(i);
if(divisionObj == null) {
continue;
}
divisionArr.setId(divisionObj.optInt("DivisionId"));
divisionArr.setName(divisionObj.optString("DivisionName"));
divisionArrayList.add(applicationType);
}
}
pd.dismiss();
} catch (JSONException e) {
e.printStackTrace();
Log.e(TAG, "Error: " + e.getMessage());
pd.dismiss();
}
Instead of Volley use Retrofit coz it'll provide you each JSON Element seperately. And to know how to use Retrofit check this tutorial.
I finally got it right, I recode the whole thing, checked my json result and here's my code
Response.Listener<JSONObject> listener = new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray divisionArr = response.getJSONArray("Division");
if(!divisionArr.equals(null)){
for(int i = 0; i < divisionArr.length(); i++){
Division division = new Division();
JSONObject divisionObj = (JSONObject) divisionArr.get(i);
division.setId(divisionObj.getInt("DivisionId"));
division.setName(divisionObj.getString("DivisionName"));
divisionList.add(division);
}
}
pd.dismiss();
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),
e.getMessage(), Toast.LENGTH_SHORT).show();
pd.dismiss();
}
}
};

How should I parse this kind of JSON?

I'm new to JSON parsing. It would be a great help if anyone would help me with parsing this kind of json array in Android.
Thank you
{
"response": 200,
"department": [
"Information Technology"
],
"subject": [
"ads(th)"
],
"professional": [
"cg(th)",
"cg(lab)"
],
"semester": [
"3A",
"5A",
"5A"
]
}
This is ur response:
{
"response": 200,
"department": [
"Information Technology"
],
"subject": [
"ads(th)"
],
"professional": [
"cg(th)",
"cg(lab)"
],
"semester": [
"3A",
"5A",
"5A"
]
}
U can do like this
String responseString="" //this string is ur web service response
try {
//JSON is the JSON code above
JSONObject jsonResponse = new JSONObject(responseString);
JSONArray department = jsonResponse.getJSONArray("department");
String hey = department.toString();
JSONArray subject = jsonResponse.getJSONArray("subject");
String sub = subject.toString();
JSONArray professional= jsonResponse.getJSONArray("professional");
String pro = professional.toString();
//like this u can parse other JsonArray
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
After getting those values in jsonarray u want to display it in spinner than u can do like this
ArrayList<String> listdata = new ArrayList<String>();
if (professional != null) {
for (int i=0;i<professional.length();i++){
listdata.add(professional.getString(i));
}
}
For Display into spinner
Spinner spinner = (Spinner) findViewById(R.id.SpinnerSpcial);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, listdata);//Pass list data of Profession
spinner.setAdapter(adapter);
Notes:
You can make custom adapter also by extending BaseAdapter or ArrayAdapter for Spinner.
Hope this will help u ... if u have any questions u can ask
Try this,
try {
JSONObject obj_result=new JSONObject(result);
String response=obj_result.getString("response");
JSONArray arr_department=obj_result.getJSONArray("department");
for(int i=0;i<arr_department.length();i++)
{
String department_name=arr_department.getString(i);
Log.d("TAG","department_name:"+department_name);
}
JSONArray arr_subject=obj_result.getJSONArray("subject");
for(int i=0;i<arr_subject.length();i++)
{
String subject_name=arr_subject.getString(i);
Log.d("TAG","subject_name:"+subject_name);
}
JSONArray arr_professional=obj_result.getJSONArray("professional");
for(int i=0;i<arr_professional.length();i++)
{
String professional_name=arr_professional.getString(i);
Log.d("TAG","professional_name:"+professional_name);
}
JSONArray arr_semester=obj_result.getJSONArray("semester");
for(int i=0;i<arr_semester.length();i++)
{
String semester_name=arr_semester.getString(i);
Log.d("TAG","semester_name:"+semester_name);
}
} catch (JSONException e) {
e.printStackTrace();
}
try { //When parsing JSON, you need try catch to handle error if occure
JSONObject fullJSON = new JSONObject("{\"response\":200,\"department\":[\"Information Technology\"],\"subject\":[\"ads(th)\"],\"professional\":[\"cg(th)\",\"cg(lab)\"],\"semester\":[\"3A\",\"5A\",\"5A\"]}");
int response = fullJSON.getInteger("response");
JSONArray departement = fullJSON.getJSONArray("department");
Log.i("", departement.getString(0));
JSONArray semester = fullJSON.getJSONArray("semester");
for(int i=0; i<semester.length(); i++) {
Log.i("semester", semester.getString(i));
}
} catch (JSONException e) {
//here's the error message you can get from
e.printStackTrace();
}
I suggest you use Gson Libray
With Gson your mapping class will be like this:
public class YourClass {
#SerializedName("response")
private Integer response;
#SerializedName("department")
private List<String> department;
#SerializedName("subject")
private List<String> subject;
#SerializedName("professional")
private List<String> professional;
#SerializedName("semester")
private List<String> semester;
}
With Gson you can transform your Json in POJO (or vice versa) easily. Check the documentation.

Retrofit error: Expected BEGIN_ARRAY but was STRING

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;

Deserialize JSON object to String Android

I am trying to implement deserialization to parse json object as a string, but my custom deserializable class is not being called.
JSON which needs to be parsed
{
"status": true,
"student": [
{
"id": 1,
"name": "",
"age": "",
"title": "",
}
]
}
My Deserializable class
public class MyDeserializer implements JsonDeserializer<StudentData> {
#Override
public StudentData deserialize(JsonElement je, Type type, JsonDeserializationContext jdc) {
try {
String content = je.getAsJsonObject().get("student").getAsString();
return new Gson().fromJson(content, StudentData)
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
Register my deserializer:-
MyDeserializer myDeserializer = new MyDeserializer();
Gson gson = new GsonBuilder().registerTypeAdapter(NotificationResponse.class, myDeserializer).create();
mRestAdapter = new RestAdapter.Builder().setServer(baseUrl).setConverter(new GsonConverter(gson)).setLogLevel(RestAdapter.LogLevel.FULL).setRequestInterceptor(new RequestInterceptor()
{
#Override
public void intercept(RequestFacade requestFacade) {
}
}).build();
I think this tutorial will help you implement a Deserializer(and might introduce some new concepts)
Try it, and see if it work for you!
For something that simple I don't think adding Gson as a dependency is worth it.
Example:
JSONObject jObj = new JSONObject(theJsonYouPostedAbove);
boolean status = jObj.getBoolean("status");
JSONArray jArr = jObj.getJSONArray("student");
for (int i = 0; i < jArr.length(); i++) {
JSONObject jo = jArr.getJSONObject(i);
int id = jo.getInt("id");
String name = jo.getString("name");
...
}

Categories

Resources