I want parse JSON response.I am unable to parse response.It shows org.json.JSONException: No value for String Response this error.
Here is my code ` public void onResponse(JSONObject response) {
Log.d("TAG", "Details:" + response);
responseTV.setText("String Response : " + response.toString());
try {
JSONObject jsonObject = response.getJSONObject("String Response"+response);
strcode = jsonObject.getString("responseCode");
strtext = jsonObject.getString("responseText");
strname = jsonObject.getString("personName");
Log.i("TAG","parseData:"+strname);
response_code.setText("" +strcode);
response_text.setText("" +strtext);
person_name.setText("" +strname);
} catch (JSONException e) {
Log.d("TAG", "profile: " + e);
}
}`
I guess you use Volley JsonObjectRequest, so you need to convert the response to a String and parse it to a JSONObject, like this:
jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null,
response -> {
try {
JSONObject jsonObject = new JSONObject(response.toString());
strcode = jsonObject.getString("responseCode");
strtext = jsonObject.getString("responseText");
strname = jsonObject.getString("personName");
Log.i("TAG","parseData:"+strname);
response_code.setText("" +strcode);
response_text.setText("" +strtext);
person_name.setText("" +strname);
} catch (JSONException e) {
Log.d("TAG", "profile: " + e);
}
}, error -> {}
);
try {
JSONObject jsonObject = response.getJSONObject(response);
strcode = jsonObject.getString("responseCode");
strtext = jsonObject.getString("responseText");
strname = jsonObject.getString("personName");
Log.i("TAG","parseData:"+strname);
response_code.setText("" +strcode);
response_text.setText("" +strtext);
person_name.setText("" +strname);
} catch (JSONException e) {
Log.d("TAG", "profile: " + e);
}
before you will do parsing , you will check all value receice by API exp :- responseCode, responseText, personName ( https://jsonlint.com/ ) , if all value you recived , check its in correct format , after that you will parse the data
you also use this , its will handle the JsonException
jsonObject.optString("responseText");
Solved this problem with this code
public void onResponse(JSONObject response) {
Log.d("TAG", "Details:" + response);
responseTV.setText("String Response : " + response.toString());
try {
// JSONObject jsonObject = response.getJSONObject(response.toString());
strcode = response.getString("responseCode");
strtext = response.getString("responseText");
strname = response.getString("personName");
Log.i("TAGParser","parseData:"+strname);
response_code.setText("" +strcode);
response_text.setText("" +strtext);
person_name.setText("" +strname);
} catch (JSONException e) {
Log.d("TAG", "profile: " + e);
}
}
Related
I am writing an application for android and using the volley library. I need to write the received data into TextResult. How to do it?
private void jsonParse() {
String url = "https://api.apixu.com/v1/current.json?key=...&q=Paris";
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("location");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject location = jsonArray.getJSONObject(i);
String name = location.getString("name");
String region = location.getString("region");
String country = location.getString("country");
TextResult.append(name + ", " + region + ", " + country + "\n\n");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
mQueue.add(request);
}
Json response example
{"location":{"name":"Paris","region":"Ile-de-France","country":"France"}}
Use this piece of code.
#Override
public void onResponse(JSONObject response) {
try {
JSONObject jsonObject = response.getJSONObject("location");
for (int i = 0; i < jsonArray.length(); i++) {
JSONArray location = jsonObject.getJSONArray(i);
String name = location.getString("name");
String region = location.getString("region");
String country = location.getString("country");
TextResult.append(name + ", " + region + ", " + country + "\n\n");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
{"location":{"name":"Paris","region":"Ile-de-France","country":"France"}}
Its not a JSONArray its a JSONObject.
First get the location from JSONObject.
String location_value=response.get("location");
JSONObject location=new JSONObject(location_value);
String name = location.getString("name");
String region = location.getString("region");
String country = location.getString("country");
TextResult.append(name + ", " + region + ", " + country + "\n\n");
I'm trying to read my data from my localhost to Android Studio. I have used volley to do this. I'm having issue getting the values from my json. Here's my json.
{"studentList":[{"username":"2011089882","password":"","section":"c4a","year":"4th"}]}
Here's my code in Android.
JsonObjectRequest jsonObjReq = new JsonObjectRequest(urlJsonObj, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
try {
String username = response.getString("username");
String section = response.getString("section");
String year = response.getString("year");
jsonResponse = "";
jsonResponse += "Username: " + username + "\n\n";
jsonResponse += "Section: " + section + "\n\n";
jsonResponse += "Year: " + year + "\n\n\n";
txtView.setText(jsonResponse);
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
hidepDialog();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(jsonObjReq);
}
Appreciate your help.
JSONArray parentArray = response.getJSONArray("studentList");
if (parentArray.length() == 0) {
//no students
} else {
for (int i = 0; i < parentArray.length(); i++) {
JSONObject finalObject = parentArray.getJSONObject(i);
String username = finalObject.getString("username");
String password = finalObject.getString("password");
String section = finalObject.getString("section");
String year = finalObject.getString("year");
}
}
this will loop through every student in "studentList"
make sure to import JSONArrayimport org.json.JSONArray;
{"studentList":[{"username":"2011089882","password":"","section":"c4a","year":"4th"}]}
Structure of your JSON response is an Object containing a list, which contains an object of type student
which contains username & password, where as you are directly trying to get username from outer object.
String username = response.getString("username");
Firstly You need to extract Object from List then access username.
JsonArray jsonArr = response.getJSONArray("studentList");
JsonObject studentObj = jsonArr.get(0);
try {
JSONObject jsonObject = new JSONObject(response.toString());
JSONArray jsonArray = jsonObject.getJSONArray("studentList");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject1 = jsonArray.getJSONObject(i);
String username = jsonObject1.getString("username");
String section = jsonObject1.getString("section");
String year = jsonObject1.getString("year");
Toast.makeText(MainActivity.this, username + " " + section + " " + year, Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
Hope this helps
I am using asyntask to enter value in database. in do in backgroud method i am calling this method.
private void callLogin() {
GetDataFromApi getDataFromApi = new GetDataFromApi(url);
if (!isTableFalse) {
Log.e("MAI A GAAYA SYNCRONISE DATA BASE MAI", "HA MAI AYA");
String message =
getDataFromApi.postSignIn().toString().trim();
syncroniseDatabase(message);
populateChurchListOnValidating
.populateChurchList(parseJsonToArrayList());
} else {
try {
loginValue =
Integer.parseInt(getDataFromApi.postSignIn());
Log.e("Login VAlue", "" + loginValue);
} catch (NumberFormatException nfe) {
nfe.printStackTrace();
}
}
}
and my syncroniseDatabase(message) is like this
private void syncroniseDatabase(String mesString) {
Log.e("URL IN SYNCRONISATION", ""+ url);
try {
InsertTable insertTable = new InsertTable();
JSONObject jsonObject = new JSONObject(mesString);
insertTable.addRowforMemberTable(jsonObject.getString(
RegistrationAppConstant.MEMBER_ID),
jsonObject.getString(RegistrationAppConstant.CLIENT_ID),
jsonObject.getString(RegistrationAppConstant.FIRSTNAME),
jsonObject.getString(RegistrationAppConstant.SURNAME),
jsonObject.getString(RegistrationAppConstant.EMAIL_ID),
jsonObject.getString(RegistrationAppConstant.PASSWORD));
Log.e("Inserting Data DONE", "" + "Done");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
and my class forInsertTable is like this
public class InsertTable {
public void addRowforMemberTable(String memberID,
String clientID, String
firstName,String surName, String emailIDString, String passWordString)
{
Log.e("NAME", "" + memberID + " " + clientID + " " + firstName + " "
+ surName + " " + emailIDString + " " +
passWordString);
ContentValues contentValue = new ContentValues();
contentValue.put(AppConstant.MCM_MEMBER_MEMEBER_ID, memberID);
contentValue.put(AppConstant.MCM_MEMBER_CLIENT_ID, clientID);
contentValue.put(AppConstant.MCM_MEMBER_FIRST_NAME, firstName);
contentValue.put(AppConstant.MCM_MEMBER_LAST_NAME, surName);
contentValue.put(AppConstant.MCM_MEMBER_EMAIL_ID, emailIDString);
contentValue.put(AppConstant.MCM_MEMBER_PASSWORD, passWordString);
Log.e("Cotent value", "" + contentValue);
try {
SplashActivity.databaseHelper.insertInToTable(
SplashActivity.databaseHelper.getWritableDatabase(),
AppConstant.MEMBER_TABLE_NAME,
contentValue);
}
catch (Exception e) {
e.printStackTrace();
}
}
}
this is my json String
[{"MemberId":77,"ClientId":37,"FirstName":"John","SurName":"Banian","Address1":null,"Address2":null,"Street":null,"Town":null,"City":null,"County":null,"State":null,"Country":null,"PostCode":null,"Mobile":null,"HomeTelephone":null,"WorkTelephone":null,"EmailId":"jbunian#yahoo.com","ConfirmEmailId":null,"Password":"123","Age":null,"Sex":null,"Profession":null,"MartialStatus":null,"Nationality":null,"Children":null,"ChurchMembershipId":null,"SecurityQuestion":null,"SecurityAnswer":null,"IsApproved":null,"IsLockedOut":null,"CreateDate":null,"LastLoginDate":null,"LastPasswordChangedDate":null,"LastLogOutDate":null,"FailedPasswordAttemptDate":null,"FailedPasswordAttemptWindowStart":null,"FailedPasswordAnswerAttemptCount":null,"FailedPasswordAnswerAttemptWindowStart":null,"Comment":null,"Active":null,"IsAuthToApproveNewMember":null,"Record_Created":null,"Record_Updated":null,"LastUpdated_LoginUserID":null,"LastUpdated_WindowsUser":null,"ClientAdminEmailId":null,"EmailListForApproval":null,"AppRegistrationStatus":null,"MemberEmailMessage":null,"AdminEmailMessage":null,"PhysicalDeviceId":null,"DeviceOS":null,"DeviceIdFromGCMorAPNS":null,"DeviceType":null}]
but my code will not executing after this line and hence i am not able to insert value.I have bold the log after which its not executing.please tell why its not executing?
Problem is that you tring to get values from JSONObject, but in reality it's JSON array. (json string starts with [.
Try to do something like this:
JSONArray jsonArray = new JSONArray(mesString);
JSONObject jsonObject = jsonArray.get(0);
insertTable.addRowforMemberTable(jsonObject.getString(RegistrationAppConstant.MEMBER_ID),
jsonObject.getString(RegistrationAppConstant.CLIENT_ID),
.....
.....
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();
}
Following is My Json File:-
"Restaurants":{
"8":{
"Res_name":"Purple Cafe and Wine Bar",
"foodtype":"American, Wine",
"city":"Seattle",
"state":"WA",
"latitude":"0",
"longitude":"0"
},
"9":{
"Res_name":"Quinn's",
"foodtype":"American, Pubs",
"city":"Seattle",
"state":"WA",
"latitude":"0",
"longitude":"0"
},
"19":{
"Res_name":"Dahlia Lounge",
"foodtype":"American",
"city":"Seattle",
"state":"WA",
"latitude":"0",
"longitude":"0"
},
},
I am Using below code for json parsing:-
try {
JSONObject jsonObj = new JSONObject(res);
JSONObject mRestaurant = jsonObj.getJSONObject("Restaurants");
String mResult = jsonObj.getString("Result");
System.out.println("mRestaurant is:- " + mRestaurant);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
The mRestaurant Value is below:-
{"487":{"state":"WA","Res_name":"SAM Taste","longitude":"0","latitude":"0","foodtype":"American","city":"Seattle"},"332":{"state":"WA","Res_name":"Luna Park Cafe","longitude":"0","latitude":"0","foodtype":"American","city":"Seattle"},"35":{"state":"WA","Res_name":"Restaurant Zoe","longitude":"0","latitude":"0","foodtype":"American, Bar","city":"Seattle"},"
but what is the next step for getting Res_Name, foodtype from above response.
Any Help would be appreciated.
The below code is next step for json parsing.
public void getdata() {
String res = mWebRequest.performGet(Constants.url+ "restaurants.php? action=searchRestaurant&lat=0&lon=0&foodtype="+ mEdttxtSearch.getText().toString() + "&state="+ mEdttxtSearch.getText().toString() + "&city="+ mEdttxtSearch.getText().toString()+ "&devType=Android");
System.out.println("res is:- " + res);
if (res != null) {
try {
JSONObject jsonObj = new JSONObject(res);
JSONObject mRestaurants = jsonObj.getJSONObject("Restaurants");
String mResult = jsonObj.getString("Result");
if (jsonObj.has("Restaurants")) {
Iterator<Object> keys = mRestaurants.keys();
while (keys.hasNext()) {
String key = (String) keys.next();
JSONObject obj = new JSONObject();
obj = mRestaurants.getJSONObject(key);
mRes_Name.add(obj.getString("Res_name"));
mLatitude.add(obj.getString("latitude"));
mLongitude.add(obj.getString("longitude"));
mState.add(obj.getString("state"));
mCity.add(obj.getString("city"));
mFood_Type.add(obj.getString("foodtype"));
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Use the get() method:
String mRestaurant = jsonObj.get("487").get("Res_name");
use gson for the same, as it supports direct conversion from json to java and java to json, please see following link:
Converting JSON to Java