My current response is
{"response":"validation error","status":"failure","code":400,"errors":["You can not add multiple items with different categories"]}
My current code is :
String errorBody = response.errorBody().string();
JSONObject jsonObject = new JSONObject(errorBody.trim());
jsonObject = jsonObject.getJSONObject("errors");
Iterator<String> keys = jsonObject.keys();
String errors = "";
while (keys.hasNext()) {
String key = keys.next();
JSONArray arr = jsonObject.getJSONArray(key);
for (int i = 0; i < arr.length(); i++) {
errors += key + " : " + arr.getString(i) + "\n";
}
}
I am trying to get the error code to see if it matches specific keywords to handle the response
i think your current code its not to good,better way for u is:
create modelClass for your json output and in retrofit calls write:
if (model.status=='failure' || model.code==400){
print(response.message) // or something like this
}
You can look through the following code snippet
call.enqueue(new Callback<PagedResponse<NotificationModel>>() {
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
#Override
public void onResponse(Call<PagedResponse<NotificationModel>> call, Response<PagedResponse<NotificationModel>> response) {
if (response.isSuccessful()) {
if (response.code() == 200) {
try {
PagedResponse<NotificationModel> notifications = (PagedResponse<NotificationModel>) response.body();
tvRecordsCount.setText("Total "+response.body().getTotal()+" Notifications ");
showNotification(notifications);
} catch (Exception e){
e.printStackTrace();
}
} else {
showToast(getApplicationContext(), "Server Error");
}
}
}
#Override
public void onFailure(Call<PagedResponse<NotificationModel>> call, Throwable t) {
showToast(getApplicationContext(), t.getMessage());
}
});
I managed to get it working with this code:
String errors = "";
String errorBody = response.errorBody().string();
JsonParser parser = new JsonParser();
JsonObject rootObj = parser.parse(errorBody.trim()).getAsJsonObject();
JsonArray errorArray = rootObj.getAsJsonArray("errors");
for (JsonElement pa : errorArray) {
errors = pa.getAsString();
}
Related
I faced with the problem while trying parse JSON array and list all values it has, I have the following JSON format
{
"sdd": {
"token":"1",
"details":[{
"type":"SOME_TYPE",
"l":,
"expiration_date":"12\/2020",
"default":true,
"expired":false,
"token":"1"
}]
}
}
JSON output I have
public void onResponse(JSONObject response) {
try {
JSONArray ja = response.getJSONArray("ssd");
for (int i = 0; i < ja.length(); i++) {
JSONObject jobj = ja.getJSONObject(i);
Log.e(TAG, "response" + jobj.getString("token"));
Log.e(TAG, "response" + jobj.getString("details"));
}
} catch(Exception e) { e.printStackTrace(); }
}
and in the log cat I getting org.json.JSONException: No value for ssd this output
You have typo. Not ssd but sdd. And also sdd is not array, but object.
So you must write like:
JSONObject jb = response.getJSONObject("sdd");
Full parsing code will be like:
public void onResponse(JSONObject response) {
try {
JSONObject sdd = response.getJSONObject("sdd");
JSONArray details = sdd.getJSONArray("details");
for (int i = 0; i < details.length(); i++) {
JSONObject jobj = details.getJSONObject(i);
Log.e(TAG, "response-type:" + jobj.getString("type"));
Log.e(TAG, "response-token:" + jobj.getString("token"));
Log.e(TAG, "response-expiration_date:" + jobj.getString("expiration_date"));
Log.e(TAG, "response-default:" + jobj.getBoolean("default"));
Log.e(TAG, "response-expired:" + jobj.getBoolean("expired"));
}
} catch(Exception e) { e.printStackTrace(); }
}
Also, let me suggest you to use gson this library will help you deserialize your json representations.
ssd is an object.
You can get the array as follows:
JSONObject jo = response.getJSONObject("sdd");
JSONArray ja = jo.getJSONArray("details");
hi you must json file isn't create
is create :
{ "sdd":{
"token":"1",
"details":[
{
"type":"SOME_TYPE",
"expiration_date":"12/2020",
"default":true,
"expired":false,
"token":"1"
}
] } }
after you can get data from code :
public void onResponse(JSONObject response) {
try {
JSONObject ssd = response.getJSONObject("ssd");
JSONArray details = ssd.getJSONArray("details");
for (int i = 0; i < details.length(); i++) {
JSONObject obj = details.getJSONObject(i);
Log.e(TAG, "response" + obj.getString("type"));
Log.e(TAG, "response" + obj.getString("expiration_date"));
Log.e(TAG, "response" + obj.getBoolean("default"));
Log.e(TAG, "response" + obj.getBoolean("expired"));
Log.e(TAG, "response" + obj.getString("details"));
}
}catch (Exception e){e.printStackTrace();}
}
The carList is declared as a public variable in the class, and the log shows that values are added in the array, yet when I call the list is empty, how to solve it with Volley response?
public void onResponse(JSONObject response) {
try {
JSONArray resArray = response.getJSONArray("result");
for(int i=0;i<resArray.length();i++) {
JSONObject car = resArray.getJSONObject(i);
String id = car.getString("id");
String brand = car.getString("brand");
String created = car.getString("created");
carList.add(new CarListItem(brand, plate_number));
Log.d(TAG, "ADDED___: " +brand + " " + plate_number);
}
Thanks
#Benp
You right, the solution is to add the recycler adapter within the onResponse body as here:
public void onResponse(JSONObject response) {
try {
JSONArray resArray = response.getJSONArray("result");
for (int i = 0; i < resArray.length(); i++) {
JSONObject car = resArray.getJSONObject(i);
String id = car.getString("id");
String brand = car.getString("brand");
String created = car.getString("created");
carList.add(new CarListItem(car_id, brand, plateNumber, color));
}
} catch (JSONException e) {
e.printStackTrace();
}
if (carList.size() > 0) {
mAdapter = new RecyclerAdapterCarsList(carList);
buildRecyclerView();
}
}
It was simple, need a tiny clue to fix it ;)
Thanks for helping
local host giving me data in browser as shown in screenshot but Volly class giving me 'Request timed out.'
*it was working well in window 8 but recently i changed my window 8 to 10 so now i am facing this problem but i think it is not happen with this reason *
public DataPoint[] getTimeAndU() {
final DataPoint[] dataPoint = new DataPoint[2000];
final DataTransmit dataTransmit = new DataTransmit(mContext) {
#Override
protected void onCompleted(String json) {
Log.v("joson",json);
if (json != null) {
// Toast.makeText(this,"sucess"+json+"",Toast.LENGTH_LONG).show();
try {
Log.v("testt","dtsfasdf");
// JSONArray ja = new JSONArray(json);
JSONObject jo = new JSONObject(json);
for(int i = 0; i < jo.length(); i++){
if (i > 1) {
JSONObject obj2 = jo.getJSONObject("a"+i);
double x = toDouble(obj2.getString("time_s"));
double y = toDouble( obj2.getString("u_mv"));
dataPoint[i] = new DataPoint(x,y);
}else{
dataPoint[i] = new DataPoint(0,0);
}
}
} catch (Throwable t) {
Log.e("app", "Could not parse malformed JSON: \"" + String.valueOf(t) + "\"");
Log.e("My App", "Could not parse malformed JSON: \"" + json + "\"");
}
}
}
};
//dataTransmit.requestJasonArray("http://192.168.1.12//Rehan/UrbanClout.php?FunctionKey=loginUser&login_name=aaa&login_pass=aaa", "Schedule");
// dataTransmit.requestJasonArray("http://192.168.1.8/ahsan_bhai_project/excel_reader/excel_reader/example.php", "Schedule");
dataTransmit.requestJasonObject("http://192.168.10.32/ahsan_bhai_project/excel_reader/excel_reader/example.php?FunctionKey=time_u","Schedule");
return dataPoint;
}
here my services in php
I want to get data from JSON and then return it in an array, but the array always return with null, because my program won't go into the onResponse method.
I want to show this data in a RecyclerView. At first it worked but now it won't work I don't know why...
private SzabadEuMusorok[] getSzabadEuMusoroks(){
if (isNetworkAvaible()){
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url("validurl").build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
alertUserAboutError();
}
#Override
public void onResponse(Call call, Response response) throws IOException {
try {
String jsonData = response.body().string();
Log.v("JSONDATA", jsonData);
if(response.isSuccessful()){
JSONArray jsonArray = new JSONArray(jsonData);
mSzabadEuMusoroks = new SzabadEuMusorok[jsonArray.length()];
for (int i = 0; i < jsonArray.length(); i++){
JSONObject jsonObject = jsonArray.getJSONObject(i);
SzabadEuMusorok szabadEuMusorok = new SzabadEuMusorok();
JSONArray elementTexts = jsonObject.getJSONArray("element_texts");
JSONObject titleObject = elementTexts.getJSONObject(0);
szabadEuMusorok.setTitile(titleObject.getString("text"));
JSONObject subjectObject = elementTexts.getJSONObject(3);
szabadEuMusorok.setSubject(subjectObject.getString("text"));
JSONObject mainObject = jsonObject.getJSONObject("files");
szabadEuMusorok.setVideoURL(mainObject.getString("url"));
mSzabadEuMusoroks[i] = szabadEuMusorok;
}
}
} catch (JSONException e) {
Log.e("JSONEXCEPTION", "Exception caught: ", e);
}
}
});
}
else{
Toast.makeText(this, R.string.network_unavaible_message, Toast.LENGTH_LONG).show();
}
return mSzabadEuMusoroks;
Your code is wrong in the logical sense. Because the call to web service is asynchronous, so when you uses "return", the array is empty, when your data is in the result doesn't matter because you already loaded the RecyclerView. The solution will be that you implement a callback function or use notifydatasetchanged in the RecyclerView.
Check the links.
Using callbacks in android
Using notifydatasetchanged
---------- notifydatasetchanged ----------
for (int i = 0; i < jsonArray.length(); i++){
JSONObject jsonObject = jsonArray.getJSONObject(i);
SzabadEuMusorok szabadEuMusorok = new SzabadEuMusorok();
JSONArray elementTexts = jsonObject.getJSONArray("element_texts");
JSONObject titleObject = elementTexts.getJSONObject(0);
szabadEuMusorok.setTitile(titleObject.getString("text"));
JSONObject subjectObject = elementTexts.getJSONObject(3);
szabadEuMusorok.setSubject(subjectObject.getString("text"));
JSONObject mainObject = jsonObject.getJSONObject("files");
szabadEuMusorok.setVideoURL(mainObject.getString("url"));
mSzabadEuMusoroks[i] = szabadEuMusorok;
}
//LINE ADDED-----------------------------------------------------
yourAdapterInTheRecyclerView.notifyDataSetChanged();
//LINE ADDED-----------------------------------------------------
I am working on an Android application. In my app I have to convert a string to JSON Object, then parse the values. I checked for a solution in Stackoverflow and found similar issue here link
The solution is like this
`{"phonetype":"N95","cat":"WP"}`
JSONObject jsonObj = new JSONObject("{\"phonetype\":\"N95\",\"cat\":\"WP\"}");
I use the same way in my code . My string is
{"ApiInfo":{"description":"userDetails","status":"success"},"userDetails":{"Name":"somename","userName":"value"},"pendingPushDetails":[]}
string mystring= mystring.replace("\"", "\\\"");
And after replace I got the result as this
{\"ApiInfo\":{\"description\":\"userDetails\",\"status\":\"success\"},\"userDetails\":{\"Name\":\"Sarath Babu\",\"userName\":\"sarath.babu.sarath babu\",\"Token\":\"ZIhvXsZlKCNL6Xj9OPIOOz3FlGta9g\",\"userId\":\"118\"},\"pendingPushDetails\":[]}
when I execute JSONObject jsonObj = new JSONObject(mybizData);
I am getting the below JSON exception
org.json.JSONException: Expected literal value at character 1 of
Please help me to solve my issue.
Remove the slashes:
String json = {"phonetype":"N95","cat":"WP"};
try {
JSONObject obj = new JSONObject(json);
Log.d("My App", obj.toString());
} catch (Throwable t) {
Log.e("My App", "Could not parse malformed JSON: \"" + json + "\"");
}
This method works
String json = "{\"phonetype\":\"N95\",\"cat\":\"WP\"}";
try {
JSONObject obj = new JSONObject(json);
Log.d("My App", obj.toString());
Log.d("phonetype value ", obj.getString("phonetype"));
} catch (Throwable tx) {
Log.e("My App", "Could not parse malformed JSON: \"" + json + "\"");
}
try this:
String json = "{'phonetype':'N95','cat':'WP'}";
You just need the lines of code as below:
try {
String myjsonString = "{\"phonetype\":\"N95\",\"cat\":\"WP\"}";
JSONObject jsonObject = new JSONObject(myjsonString );
//displaying the JSONObject as a String
Log.d("JSONObject = ", jsonObject.toString());
//getting specific key values
Log.d("phonetype = ", jsonObject.getString("phonetype"));
Log.d("cat = ", jsonObject.getString("cat");
}catch (Exception ex) {
StringWriter stringWriter = new StringWriter();
ex.printStackTrace(new PrintWriter(stringWriter));
Log.e("exception ::: ", stringwriter.toString());
}
just try this ,
finally this works for me :
//delete backslashes ( \ ) :
data = data.replaceAll("[\\\\]{1}[\"]{1}","\"");
//delete first and last double quotation ( " ) :
data = data.substring(data.indexOf("{"),data.lastIndexOf("}")+1);
JSONObject json = new JSONObject(data);
To get a JSONObject or JSONArray from a String I've created this class:
public static class JSON {
public Object obj = null;
public boolean isJsonArray = false;
JSON(Object obj, boolean isJsonArray){
this.obj = obj;
this.isJsonArray = isJsonArray;
}
}
Here to get the JSON:
public static JSON fromStringToJSON(String jsonString){
boolean isJsonArray = false;
Object obj = null;
try {
JSONArray jsonArray = new JSONArray(jsonString);
Log.d("JSON", jsonArray.toString());
obj = jsonArray;
isJsonArray = true;
}
catch (Throwable t) {
Log.e("JSON", "Malformed JSON: \"" + jsonString + "\"");
}
if (object == null) {
try {
JSONObject jsonObject = new JSONObject(jsonString);
Log.d("JSON", jsonObject.toString());
obj = jsonObject;
isJsonArray = false;
} catch (Throwable t) {
Log.e("JSON", "Malformed JSON: \"" + jsonString + "\"");
}
}
return new JSON(obj, isJsonArray);
}
Example:
JSON json = fromStringToJSON("{\"message\":\"ciao\"}");
if (json.obj != null) {
// If the String is a JSON array
if (json.isJsonArray) {
JSONArray jsonArray = (JSONArray) json.obj;
}
// If it's a JSON object
else {
JSONObject jsonObject = (JSONObject) json.obj;
}
}
Using Kotlin
val data = "{\"ApiInfo\":{\"description\":\"userDetails\",\"status\":\"success\"},\"userDetails\":{\"Name\":\"somename\",\"userName\":\"value\"},\"pendingPushDetails\":[]}\n"
try {
val jsonObject = JSONObject(data)
val infoObj = jsonObject.getJSONObject("ApiInfo")
} catch (e: Exception) {
}
Here is the code, and you can decide which
(synchronized)StringBuffer or
faster StringBuilder to use.
Benchmark shows StringBuilder is Faster.
public class Main {
int times = 777;
long t;
{
StringBuffer sb = new StringBuffer();
t = System.currentTimeMillis();
for (int i = times; i --> 0 ;) {
sb.append("");
getJSONFromStringBuffer(String stringJSON);
}
System.out.println(System.currentTimeMillis() - t);
}
{
StringBuilder sb = new StringBuilder();
t = System.currentTimeMillis();
for (int i = times; i --> 0 ;) {
getJSONFromStringBUilder(String stringJSON);
sb.append("");
}
System.out.println(System.currentTimeMillis() - t);
}
private String getJSONFromStringBUilder(String stringJSONArray) throws JSONException {
return new StringBuffer(
new JSONArray(stringJSONArray).getJSONObject(0).getString("phonetype"))
.append(" ")
.append(
new JSONArray(employeeID).getJSONObject(0).getString("cat"))
.toString();
}
private String getJSONFromStringBuffer(String stringJSONArray) throws JSONException {
return new StringBuffer(
new JSONArray(stringJSONArray).getJSONObject(0).getString("phonetype"))
.append(" ")
.append(
new JSONArray(employeeID).getJSONObject(0).getString("cat"))
.toString();
}
}
May be below is better.
JSONObject jsonObject=null;
try {
jsonObject=new JSONObject();
jsonObject.put("phonetype","N95");
jsonObject.put("cat","wp");
String jsonStr=jsonObject.toString();
} catch (JSONException e) {
e.printStackTrace();
}