This is part of an AsyncTask that calls a web service that returns a JSON result. As you can see I hard coded the actual JSON return object. This was pulled directly from the error I got that specified it could not create the JSON object from the string object I was passing in, which is the variable result. That error occured when it hit new JSONObject(result) in the ParseResults method. Why would hard coding the exact string work but not the string being passed in?
#Override
protected void onPostExecute(String result) {
try {
result = "{\"Response\":{\"ReturnCode\":200,\"ReturnMessage\":\"Information Successfully Retrieved\",\"ReturnData\":null,\"ReturnClass\":{\"PRO_ID\":\"11111111-1111-1111-1111-111111111111\",\"PRO_FirstName\":\"SILVER\",\"PRO_LastName\":\"HIYO\"},\"FriendlyErrorMessage\":null}}";
JSONObject jsonObject = new ApiMethods().ParseResult(result);
ParseResults method snippet.
public JSONObject ParseResult(String result) throws JSONException
{
JSONObject returnedObject = new JSONObject();
try
{
JSONObject jsonObject = new JSONObject(result);
Also below, as i stated in a comment to another user, is the return statement that is returning the data. This is being returned from a .NET MVC application. I added in the UTF8 when that was mentioned and still get the same error.
return Json(data: new { Response = returnValue }, contentType: "application/json", contentEncoding: System.Text.Encoding.UTF8, behavior: JsonRequestBehavior.AllowGet);
And the entire error message:
org.json.JSONException: Value {"Response":{"ReturnCode":200,"ReturnMessage":"Information Successfully Retrieved","ReturnData":null,"ReturnClass":{"PRO_ID":"11111111-1111-1111-1111-111111111111","PRO_FirstName":"Silver","PRO_LastName":"HIYO"},"FriendlyErrorMessage":null}} of type java.lang.String cannot be converted to JSONObject
Seems like your hardcoded json object is not a valid json object. This may be the reason why it throws exception. Check validitiy of json object here first.
type java.lang.String cannot be converted to JSONObject
This means "Use getString() for String"
getJSONObject() may cause this error.
class Response {
String returnMessage;
...
}
Response response;
response.returnMessage= "msg";
JSONObjct obj;
obj = response.getJSONObject("ReturnMessage"); // cannot be converted
It maybe a encoding problem. Browser (and source editor) may have converted the result string encoding.
Q: ... I am storing items for the JSON data as Strings which is resulting in some odd character appearing
A: new String(jo.getString("name").getBytes("ISO-8859-1"), "UTF-8");
Android JSON CharSet UTF-8 problems
Hard coded JSON string is valid. If you want to try, replace (\") with (") and paste it to the checker.
{
"Response": {
"ReturnCode": 200,
"ReturnMessage": "Information Successfully Retrieved",
"ReturnData": null,
"ReturnClass": {
"PRO_ID": "11111111-1111-1111-1111-111111111111",
"PRO_FirstName": "SILVER",
"PRO_LastName": "HIYO"
},
"FriendlyErrorMessage": null
}
}
JSON object is like a structure (or class)
It looks like this.
class Response {
int ReturnCode = 200;
String ReturnMessage = "Information Successfully Retrieved";
...
}
Sample code.
protected void onPostExecute(String result)
{
JSONObject jsonObject;
JSONObject response;
int returnCode;
String returnMessage;
//JSONObject returnMessage;
result = "{\"Response\":{\"ReturnCode\":200,\"ReturnMessage\":\"Information Successfully Retrieved\",\"ReturnData\":null,\"ReturnClass\":{\"PRO_ID\":\"11111111-1111-1111-1111-111111111111\",\"PRO_FirstName\":\"SILVER\",\"PRO_LastName\":\"HIYO\"},\"FriendlyErrorMessage\":null}}";
try
{
jsonObject = new JSONObject(result);
response = jsonObject.getJSONObject("Response");
returnCode = response.getInt("ReturnCode");
returnMessage = response.getString("ReturnMessage");
//returnMessage = response.getJSONObject("ReturnMessage"); // This may cause same error
}
catch (JSONException e)
{
e.printStackTrace();
}
}
Use this site to validate your json string
http://jsonlint.com/
Related
I need to show response on Sign Up, below is my JSON Response.
I should show password is too short(minimum is 5 characters) into one string
{ errors: { password: [ "is too short (minimum is 5 characters)" ] } }
And also I need to parse the response from the following JSON data
as Signature has already been taken
{ errors: { signature: [ "has already been taken" ] } }
Please tell me how to parse the particular data from the JSON data.
Thanks in advance!!!!
You can use below method to parse your data.
private String parseJsonData(String jsonResponse) {
try {
JSONObject jsonObject = new JSONObject(jsonResponse);
JSONObject errorJsonObject = jsonObject.getJSONObject("errors");
JSONArray jsonArray = null;
//has method
if (errorJsonObject.has("password")) {
jsonArray = errorJsonObject.optJSONArray("password");
} else if (errorJsonObject.has(" signature")) {
jsonArray = errorJsonObject.optJSONArray("signature");
}
String errorMessage = jsonArray.getString(0);
return errorMessage;
} catch (JSONException e) {
e.printStackTrace();
return null;
}
}
You can replace unwanted symbols like below code:
errorMessage.repalce("[","");
errorMessage.repalce("]","");
errorMessage.repalce("/"","");
You can use Google's Gson library to do that using the following steps:
Add dependency in your build.gradle(Module:app) file.
dependencies {
implementation 'com.google.code.gson:gson:2.8.5'
}
For latest version of gson library, click here
To parse JSON string to an object use the code below:
Gson gson = new Gson();
// I'm fetching my session stored JSON string
// You can fetch as per your requirement
String jsonStr = session.getJsonStr();
MyObject myObject = (MyObject) gson.fromJson(jsonStr, MyObject.class);
And if you need to convert an object to a JSON string, you can use the below code:
// I'm fetching my session stored Object here
// You can fetch as per your requirement
MyObject myObject = session.getMyObject();
String jsonStr = gson.toJson(myObject);
Make sure you design your object appropriate for the JSON string to match the data types. If you are not sure of the data types in the JSON, you can use this site or any parse and view website to view them.
Hope it helps!
Just try this,
try {
String tost = null;
JSONObject object = new JSONObject(json);
JSONObject errorObject = object.getJSONObject("errors");
if (errorObject.has("password")){
tost = "password "+errorObject.getJSONArray("password").get(0).toString();
} else if (errorObject.has("signature")){
tost = "signature "+errorObject.getJSONArray("signature").get(0).toString();
}
Toast.makeText(MainActivity.this, tost, Toast.LENGTH_SHORT).show();
}catch (Exception e){
e.printStackTrace();
}
I am getting an error org . json.JSONException: End of input at character 0
This is my Code :-
JSONObject jObjError = new JSONObject(response.errorBody().string());
Log.e("Error","::"+jObjError.getString("error_codes"));
and this is my JSON
{
"errors":{
"provider":["already has an appointment scheduled at this time."]
},
"error_codes":["provider_unavailable"]
}
Can anyone help me with this
The key point here is that you're trying to get a string from an array, not directly from an object. The correct way of parsing this would be:
JSONObject jObjError = new JSONObject(response.errorBody().string());
JSONArray errorArray = jObjError.optJSONArray("error_codes");
for(int i = 0;i<errorArray.size;i++) {
Log.e("Error","::"+errorArray.get(i));
}
If response is your returned JSON, you should pass it directly as parameter is it's of type String
JSONObject jo=new JSONObject(response);
and then do whatever else. because your error messages are customized and returned as json string so this is interpreted as successful request with customized messages.
I am using Retrofit which uses GSON for parsing.The server will check the parameter i am sending and returns two responses Accordingly.
If the parameter is valid i am getting the following response
[
true
]
If it is not valid then i get response as,
[
"Sorry, <em class=\"placeholder\">names#gmail.inp</em> is not recognized as a user name or an e-mail address."
]
This is the call method i am using.
#Override
public void onResponse(Call<String> call, Response<String> response) {
mProgressBar.setVisibility(View.GONE);
Log.d("Response ", ""+response);
}
here response.body giving me as null. But there is a response.which is viewable in OKHttp Log.
you can try this
JSONArray jArray=new JSONArray(yourString);
String str=jArray.getString(0);;
if(str.equalsIgnoreCase("true")
{
//your code
}else
{
}
JSONArray jarray = new JSONObject(jsonString);
for (int i = 0; i < jarray.length(); i++) {
String string = jarray.getString(i);
log.e("String",string);
}
that's working great. Please try this.
You can use JsonParser provided by Gson. It will parse the json input to dynamic JsonElement.
Look at MByD example:
public String parse(String jsonLine) {
JsonElement jelement = new JsonParser().parse(jsonLine);
JsonObject jobject = jelement.getAsJsonObject();
jobject = jobject.getAsJsonObject("data");
JsonArray jarray = jobject.getAsJsonArray("translations");
jobject = jarray.get(0).getAsJsonObject();
String result = jobject.get("translatedText").toString();
return result;
}
since the server return diffrent codes
can you try
Call<Void>
and check the response code
this might work for now until you know what is wrong void will not parse any thing so it shouldn't cause a crash
///////
did you try
Call<ArrayList<String>>
also are you sure the server returns 200 in both cases ?
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Determine whether JSON is a JSONObject or JSONArray
I have a server that returns some JSONArray by default, but when some error occurs it returns me JSONObject with error code. I'm trying to parse json and check for errors, I have piece of code that checks for error:
public static boolean checkForError(String jsonResponse) {
boolean status = false;
try {
JSONObject json = new JSONObject(jsonResponse);
if (json instanceof JSONObject) {
if(json.has("code")){
int code = json.optInt("code");
if(code==99){
status = true;
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return status ;
}
but I get JSONException when jsonResponse is ok and it's a JSONArray (JSONArray cannot be converted to JSONOBject)How to check if jsonResponse will provide me with JSONArray or JSONObject ?
Use JSONTokener. The JSONTokener.nextValue() will give you an Object that can be dynamically cast to the appropriate type depending on the instance.
Object json = new JSONTokener(jsonResponse).nextValue();
if(json instanceof JSONObject){
JSONObject jsonObject = (JSONObject)json;
//further actions on jsonObjects
//...
}else if (json instanceof JSONArray){
JSONArray jsonArray = (JSONArray)json;
//further actions on jsonArray
//...
}
You are trying the convert String response you get from Server into JSONObject which is causing the Exception. As you said you will get the JSONArray from Server, you try to convert into JSONArray. Please refer this link which will help you when to convert string response to JSONObject and JSONArray. If you response starts with [ (Open Square Bracket) then convert it to JsonArray as below
JSONArray ja = new JSONArray(jsonResponse);
if your response starts with { (open flower Bracket) then convert it to
JSONObject jo = new JSONObject(jsonResponse);
I am trying to convert an json string returned from a web service to local class object on android.
but got error: java.lang.String cannot be converted to JSONArray
the string returned is:
[{"Id":592,"RadioName":"CRI怀旧金曲(128Kbps)","RadioAddress":"mmst","Priority":0,"GroupId":14,"GroupDesc":"热门","RadioCountry":"China(中国)","Valid":1,"Vip":0,"LanguageDesc":"China(中国)"},{"Id":594,"RadioName":"猫扑网络电台(32Kbps)","RadioAddress":"mmst","Priority":1,"GroupId":14,"GroupDesc":"热门","RadioCountry":"China(中国)","Valid":1,"Vip":0,"LanguageDesc":"China(中国)"}]
the code I am using is:
String result= convertStreamToString(instream);
try {
JSONArray responseObject = new JSONArray(result);
} catch (JSONException e) {
e.printStackTrace();
}
if I manually assign above returned string to a String variable, the convert is successful, no idea how is that. please help.