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();}
}
Related
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();
}
I'm using volley to get json object, I'm getting data like this
{"resultUser":19}
{"resultUser2":13}
How to get either the second one (resultuser2) or both?
try {
JSONObject o = new JSONObject(response);
String data = (String) o.get("resultUser2");
if (!data.equals("")) {
Toast.makeText(getApplicationContext(), "user2 id" + data, Toast.LENGTH_LONG).show();
//UserDetailsActivty.this.finish();
} else {
Toast.makeText(getApplicationContext(), "Ohh! Sorry,,Signing Up Failed ", Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
you can use JsonArray to iterate through all the jsonobjects like this
try {
JSONArray jsonArray = new JSONArray(response);
for (int i =0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.get(i);
//do whatever you want to do with the data
}
} catch(Exception e) {
}
My json is like this
{
"results": [{
"syllabus": "CBSE",
"grade": "5",
"subject": "Kannada",
"topic": "Grammar Level 1",
"id": 28
}]
}
Using Volley
JsonArrayRequest req = new JsonArrayRequest(urlJsonArry,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
try {
// Parsing json array response
// loop through each json object
jsonResponse = "";
for (int i = 0; i < response.length(); i++) {
JSONObject person = (JSONObject) response
.get(i);
System.out.println(person.toString());
String syllabus = person.getString("syllabus");
String grade= person.getString("grade");
jsonResponse += "Name: " + syllabus + "\n\n";
jsonResponse += "Email: " + grade + "\n\n";
}
Your Json have an object and then array.. try like this
JsonObjectRequest req = new JsonObjectRequest(urlJsonArry,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
try {
JSONOArray array = response.getJSONArray("results")
// Parsing json array response
// loop through each json object
jsonResponse = "";
for (int i = 0; i < array.length(); i++) {
JSONObject person = (JSONObject) array
.get(i);
System.out.println(person.toString());
String syllabus = person.getString("syllabus");
String grade= person.getString("grade");
jsonResponse += "Name: " + syllabus + "\n\n";
jsonResponse += "Email: " + grade + "\n\n";
}
if (!result.equalsIgnoreCase("")) {
try {
JSONObject jsonObject = new JSONObject(result); //result is what you get responce
JSONArray jsonArray = jsonObject.optJSONArray("results");
if (jsonArray != null) {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObjects = jsonArray.optJSONObject(i);
String syllabus = jsonObjects.optString("syllabus");
Int grade = jsonObjects.optInt("grade");
String subject = jsonObjects.optString("subject");
String topic = jsonObjects.optString("topic");
Int id = jsonObjects.optInt("id");
}
} else {
Log.e("", "error parse json", "--->" + e.getMessage());
}
} catch (Exception e) {
Log.e("", "error parse json", "--->" + e.getMessage());
}
} else {
Log.e("", "error parse json", "--->" + e.getMessage());
}
Here is my JSON
{
"keys": [
"10_Ultimate",
"20_Yemensoft"
]
}
When I hit directly in the Url I am getting correct response but not from Android. Also I have seen in jsonlint the JSON format is correct. But I am getting following message:
org.json.JSONException: Unterminated array at character 11 of
[B#41c16df8
when i hit the Url
http://192.168.0.103:8080/AndroidRest/financial/finList
I am getting correct json response Also i validated in jsonlint.com
{
"keys" : [ "10_Ultimate", "20_Yemensoft" ]
}
when i try to deserialize from android it saysorg.json.JSONException: Unterminated array at character 11
#Override
public void onSuccess(int statusCode, Header[] headers, byte[] response) {
JSONObject jsnObj = new JSONObject();
String res = response.toString();
try {
JSONObject json = new JSONObject(res);
JSONArray jsnArry = json.getJSONArray("keys");
for (int i = 0 ; i < jsnArry.length() ; i++){
jsnObj = jsnArry.getJSONObject(i);
}
Log.d("jsnObj",jsnObj.toString());
Log.d("jsnArry",jsnArry.toString());
} catch (JSONException e) {
e.printStackTrace();
}
Log.d("The Positive are",res);
}
You can try this (I have tested):
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String jsonString = "{\n" +
" \"keys\" : [ \"10_Ultimate\", \"20_Yemensoft\" ]\n" +
"}";
JSONObject jsnObj = new JSONObject();
try {
JSONObject json = new JSONObject(jsonString);
JSONArray jsnArry = json.getJSONArray("keys");
for (int i = 0 ; i < jsnArry.length() ; i++){
jsnObj.put(String.valueOf(i), jsnArry.getString(i));
}
Log.d("jsnObj", jsnObj.toString());
Log.d("jsnArry",jsnArry.toString());
} catch (JSONException e) {
e.printStackTrace();
}
Log.d("The Positive are", jsonString);
}
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();
}