Unterminated object at jsonobject line 19? - java

Am new to android development am making simple login application using volley and getting json response from server like this:
json response:-
{"loginResult":"{\"UserLoginID\":864,\"UserID\":864,\"EmployeeCode\":\"PI4264\",\"Password\":\"XXXX\",\"IsPasswordChanged\":false,\"ModuleName\":\"XXX\",\"ModuleID\":1,\"EmployeeName\":\"XXXX \"}"}
When i try to parse this jsonobect am getting :
Unterminated object at 19 jsonexception so far what i have tried is to parse is
String resp = response.toString().replaceAll("\\\\", "");
try {
JSONObject yog = new JSONObject(resp);
int yogs=yog.getInt("UserID");
Toast.makeText(getApplicationContext(), resp, Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
e.printStackTrace();
}
don't know where am making mistake can anybody teach me am i doing it in right way!!!

You should change your code to this:
String resp = response.toString().replaceAll("\\\\", "");
try {
JSONObject yog = new JSONObject(resp);
JSONObject loginObject = new JSONObject(yog.getString("loginResult"));
int yogs=loginObject.getInt("UserID");
Toast.makeText(getApplicationContext(), resp, Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
e.printStackTrace();
}
I executed the code and didn't get the error:
JSONObject yog = new JSONObject("{\"loginResult\":\"{\\\"UserLoginID\\\":864,\\\"UserID\\\":864,\\\"EmployeeCode\\\":\\\"PI4264\\\"," +
"\\\"Password\\\":\\\"XXXX\\\",\\\"IsPasswordChanged\\\":false,\\\"ModuleName\\\":\\\"XXX\\\",\\\"ModuleID\\\":1,\\\"EmployeeName\\\":\\\"XXXX " +
"\\\"}\"}");
JSONObject loginObject = new JSONObject(yog.getString("loginResult"));
int yogs=loginObject.getInt("UserID");
Toast.makeText(getApplicationContext(), String.valueOf(yogs), Toast.LENGTH_SHORT).show();

You are making an un-necessary string sanitization.
Just remove replaceAll command. and use following code :
try {
JSONObject yog = new JSONObject(response);
JSONObject loginObject = new JSONObject(yog.getString("loginResult"));
int yogs=loginObject.getInt("UserID");
System.out.println(yogs);
}
catch (JSONException e) {
e.printStackTrace();
}
This should work fine after that.

Related

onResponse(String response) try { JSONObject jsonObject=new JSONObject(response);java.lang.String cannot be converted to JSONObject

I can't find answer. tried many websites including this. i want to know where from the problem coming.
Error is: org.json.JSONException: Value connection of type java.lang.String cannot be converted to JSONObject
This is my andorid code:-
StringRequest stringRequest=new StringRequest(Request.Method.POST, URL_LOGIN,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject=new JSONObject(response);
String success=jsonObject.getString("success");
JSONArray jsonArray=jsonObject.getJSONArray("login");
if (success.equals("1")){
for (int i=0;i<jsonArray.length();i++) {
JSONObject object=jsonArray.getJSONObject(i);
String uname=object.getString("username").trim();
String email=object.getString("email");
Toast.makeText(MainActivity.this, "Login Successful!!! \n Your Name: "+uname+"\nYour Email: "+email, Toast.LENGTH_SHORT).show();
loading.setVisibility(View.GONE);
}
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(MainActivity.this," Error!!"+e.toString(),Toast.LENGTH_LONG).show();
loading.setVisibility(View.GONE);
signin_btn.setVisibility(View.VISIBLE);
}
}
},
Logcat
2019-09-06 19:40:37.264 7944-7944/com.example.project W/System.err:
org.json.JSONException: Value connection of type java.lang.String
cannot be converted to JSONObject 2019-09-06 19:40:37.264
7944-7944/com.example.project W/System.err: at
org.json.JSON.typeMismatch(JSON.java:111) 2019-09-06 19:40:37.264
7944-7944/com.example.project W/System.err: at
org.json.JSONObject.(JSONObject.java:160) 2019-09-06
19:40:37.264 7944-7944/com.example.project W/System.err: at
org.json.JSONObject.(JSONObject.java:173)
As the exception implies, the response String cannot be converted to a JSONObject:
public JSONObject(java.lang.String source) throws JSONException
Throws: JSONException - If there is a syntax error in the source string or a duplicated key.
from: http://stleary.github.io/JSON-java/org/json/JSONObject.html#JSONObject-java.lang.String-
Ensure your response String (obtained from a POST request to URL_LOGIN) is indeed a valid JSON string. Either write an end-to-end test incorporating the system hosting URL_LOGIN or manually test with a client such as Postman that the system serving URL_LOGIN works as intended given the request from your application.
Your Retrofit callback response listener will be Response type of Retrofit.
Make your code like this and it will work fine.
StringRequest stringRequest=new StringRequest(Request.Method.POST, URL_LOGIN,
new Response.Listener<Response>() {
#Override
public void onResponse(Response response) {
try {
JSONObject jsonObject=new JSONObject(response.body());
String success=jsonObject.getString("success");
JSONArray jsonArray=jsonObject.getJSONArray("login");
if (success.equals("1")){
for (int i=0;i<jsonArray.length();i++) {
JSONObject object=jsonArray.getJSONObject(i);
String uname=object.getString("username").trim();
String email=object.getString("email");
Toast.makeText(MainActivity.this, "Login Successful!!! \n Your Name: "+uname+"\nYour Email: "+email, Toast.LENGTH_SHORT).show();
loading.setVisibility(View.GONE);
}
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(MainActivity.this," Error!!"+e.toString(),Toast.LENGTH_LONG).show();
loading.setVisibility(View.GONE);
signin_btn.setVisibility(View.VISIBLE);
}
}
},
L
when I use these statements my code doesn't show a problem
JSONObject js=new JSONObject(response);
final String res = js.getString("result");
but when I don't use it work correctly:
try {
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, HTTP.UTF_8));
HttpResponse httpResponse = httpClient.execute(httpPost);
final String response = EntityUtils.toString(httpResponse.getEntity());
JSONObject js=new JSONObject(response);
final String res = js.getString("result");
JSONObject js=new JSONObject(response);
final String res = js.getString("result");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "Problem", Toast.LENGTH_SHORT).show();
}
});
}
catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}

Error converting JSONArray to JSONObject

I am trying to extract and process some JSON data, but it is erroring when I try. This is my code:
protected void onPostExecute(String s) {
String err=null;
try {
JSONObject root = new JSONObject(s);
JSONObject user_data = root.getJSONObject("user_data");
LASTNAME = user_data.getString("lastname");
PASSWORD = user_data.getString("password");
EMAIL = user_data.getString("email");
} catch (JSONException e) {
e.printStackTrace();
err = "Exception: "+e.getMessage();
}
Intent i = new Intent(ctx, MainActivity.class);
i.putExtra("lastname", LASTNAME);
i.putExtra("email", EMAIL);
i.putExtra("password", PASSWORD);
i.putExtra("err", err);
startActivity(i);
}
But this is the error:
org.json.JSONException: Value [] at user_data of type org.json.JSONArray cannot be converted to JSONObject
I think you have problem with casting Array to Object.
[..] means it is JSONArray.
{..} means it is JSONObject.
try {
JSONArray jObj = new JSONArray(json);
//This is how you get value from 1 element in JSONArray
String firstObjectValue = jObj.getString(0);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
If you looking for value need you to iterate all JSONArray
by doing some simple loop.
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(result);
JSONArray jsonARRAY = jsonObject.getJSONArray("nameOfJSONArray");
for (int i = 0; i < jsonARRAY.length(); i++) {
JSONObject jsonOBJECT = (JSONObject) jsonARRAY.get(i);
String yourValue = jsonOBJECT.getString("valueKey");
}
} catch (JSONException e) {
e.printStackTrace();
}
It seems like your "user_data" is coming as json array instead of json object that you are trying to access.
you can use root.optJSONObject("user_data") to determine & return json object if your user_data is json object or will return null.

How Read JSON Array, Android Java

I need to read this JSON array :
[{
"1":{"id":"0","name":"first"},
"2":{"id":"1","name":"second"}
}]
I use this code
JSONObject jsonObject = null;
for(int i=0; i < array.length(); i++)
{
try
{
jsonObject = array.getJSONObject(i);
System.out.println("Data: " + jsonObject.getString("id"));
}
catch (JSONException e)
{
Log.e("Get Data from JSON Array ..", "Error: " + e.getMessage());
}
}
But the array length = 1 always
and the error appear : no value for id
The method to return JSON Array ..
public static JSONArray getJSONArrayFromUrl(String url)
{
String str = "{\"Array\":["; // I add it because the JSON return from the site not contains root ..
HttpResponse response;
HttpClient myClient = new DefaultHttpClient();
HttpPost myConnection = new HttpPost("url);
try
{
response = myClient.execute(myConnection);
str += EntityUtils.toString(response.getEntity(), "iso-8859-1") + "]}";
}
catch (ClientProtocolException e) {
Log.e("Client Protocol Exception", "Error: " + e.getMessage());
}
catch (IOException e) {
Log.e("IO Exception", "Error: " + e.getMessage());
}
JSONObject obj = null;
JSONArray array = null;
try {
obj = new JSONObject(str);
array = obj.getJSONArray("Array");
}
catch (JSONException e) {
Log.e("JSON Exception", "Error: " + e.getMessage());
}
return array;
}
How to solve it or how to read the JSON text ..
Thanks ,,
At first you need to create a class like this one:
public class ExampleClass {
int id;
String name;
}
And then you call it in your try:
Gson gson = new Gson();
Type listOfTestObject = new TypeToken<ArrayList<ExampleClass>>() { }.getType();
ArrayList<ExampleClass> arrayInJSON = gson.fromJson(exampleJSONObject, listOfTestObject);
Then, you can use the response from JSON to get the size:
arrayInJSON.size();
It is an array with one element on it
[{
"1":{"id":"0","name":"first"},
"2":{"id":"1","name":"second"}
}]
becouse it look like [{...}]
here {...} is a map of 2 elements it is not array
jsonObject.getString("1").getString("id") in your code should return what you need

JSON object showing null pointer exception

I want to post data to the url and getting Null pointer exception
My JSON URL contains
{
"Details":
[
{
"Status":"NO UPDATES"
}
]
}
I'm getting the error the line:
String status = object.getString("Status").trim(); //error Line
Full code:
btnPost = (Button)findViewById(R.id.btnPost);
btnPost.setOnClickListener(this);
btnPost.setOnClickListener(new OnClickListener()
{
#SuppressWarnings("null")
#Override
public void onClick(View arg0)
{
try
{
String postReceiverUrl = "http://";
Log.v(TAG, "postURL: " + postReceiverUrl);
// HttpClient
#SuppressWarnings("resource")
HttpClient httpClient = new DefaultHttpClient();
// post header
HttpPost httpPost = new HttpPost(postReceiverUrl);
jsonobject.put("IDNo", IDNo.getText().toString());
jsonobject.put("Position", Position.getText().toString());
jsonobject.put("Data", Data.getText().toString());
HttpResponse response = httpClient.execute(httpPost);
String jsonResult = inputStreamToString(response.getEntity().getContent()).toString();
Log.v("jsonResult",jsonResult);
JSONObject object = new JSONObject(jsonResult);
String status = object.getString("Status").trim();
Toast.makeText(getBaseContext(), "Please wait...",100).show();
if(status.toString().equals("SUCCESS"))
{
Intent i = new Intent(LoginPage.this,MainActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
if(status.toString().equals("FAILED"))
{
Toast.makeText(getBaseContext(), "Wrong Credentials",100).show();
}
else
{
Toast.makeText(getBaseContext(), "Details Inserted",100).show();
}
}
catch(Exception e)
{
e.printStackTrace();
}
catch (JSONException e)
{
e.printStackTrace();
}
catch (ClientProtocolException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
});
Do proper parsing of the JSON as , you see yours response:-
{ "Details":[{"Status":"NO UPDATES"}]}
So Firstly try to make the object of the JSONObject than after the JSONArray , look at below example:-
JSONObject jsonObject = new JSONObject(jsonResult);
JSONArray detailsArray = jsonObject.getJSONArray("Details");
String status = dataArray.getJSONObject(0).getString("status");
Toast.makeText(getBaseContext(), "Please wait...",100+status).show();
your code should be like this
JSONObject object = new JSONObject(jsonResult);
JSONOArray details = object.getJSONArray("Details");
for (int i = 0; i < details.length(); i++) {
JSONObject c = details.getJSONObject(i);
String status = c.getString("Status");
}
Toast.makeText(getBaseContext(), "Please wait...",100).show();
Modift String status = object.getString("Status").trim(); to
String status = object.get("Details").getAsJsonArray()[0].getString("Status").trim();
You are using getString("Status") which may return null if key is not available in JSON. I'd suggest you to use optString("Status") it'll return blank String if key is not available.
JSONObject jsonObject = new JSONObject(stringJSON);
JSONArray jsonArray = jsonObject.optJSONArray("Details");
if(jsonArray != null){
for(int i = 0; i < jsonArray.length(); i++){
JSONObject jObject = jsonArray.optJSONObject(i);
if(jObject != null){
String strStatus = jObject.optString("Status");
}
}
}
Try this code
JSONObject object = new JSONObject(jsonResult);
JSONArray array=object.getJsonarray("Details");
for(int i=0;i<array.length();i++)
{
JSONObject innerObject=array.getJsonObject(i);
String s= innerObject.getString("Status");
}
If at any point in your code, org.json.JSONObject json_object becomes null and you wish to avoid NullPointerException (java.lang.NullPointerException), then simply check as following:
if(json_object == null) {
System.out.println("json_object is found as null");
}
else {
System.out.println("json_object is found as not null");
}

JSON array is not being created from a stream

Basically, I'm sending a request to a server, and its reponse is "{"Result":"OK"}", which I can retrieve, however when I try and use the repsonse in my processing method:
public void ProcessData(java.lang.String stream)
{
JSONArray jsonArray;
try
{
jsonArray = new JSONArray(stream);
for(int i=0; i<jsonArray.length(); i++)
{
JSONObject jsonObject = jsonArray.getJSONObject(i);
String itemText = jsonObject.getString("text");
Response = itemText;
}
}catch (JSONException e)
{
e.printStackTrace();
}
}
if stream is "{"Result":"OK"}" it fails on this line
jsonArray = new JSONArray(stream);
Any ideas?
Because it's not a json array its a json object (starts with {)..
jsonobject = new JSONObject(stream);
doing wrong your trying to parse JsonObject to JsonArray try like
try {
JSONObject jobj = new JSONObject(Respones);
String userid = jobj.getString("Result");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
This jsonStr is a JsonObject format:
{name:value}
not a jSONArray format:
[{name:value}]
you must use:
JSONObject obj=new JSONObject(stream)
couldn't use new JSonArray(stream);
There's no JSONArray there, just a JSONObject
jsonArray = new JSONObject(stream);

Categories

Resources