String to JsonObject returns null - android

I have the following method for parsing a sample String to JSONObject:
private JSONObject test() {
try {
String responseData = "{\"m_tani\":[{\"tani_cd\":\"02\",\"tani_nm\":\"cs\"},{\"tani_cd\":\"03\",\"tani_nm\":\"pc\"}]}";
Log.i("Json", responseData.toString());
JSONObject json = new JSONObject(responseData);
return json;
} catch (Exception e) {
e.printStackTrace();
Log.i("Json", "exception");
}
Log.i("Json", null);
return null;
}
The responseData is:
{"m_tani":[{"tani_cd":"02","tani_nm":"cs"},{"tani_cd":"03","tani_nm":"pc"}]}
When I debug it, from the line JSONObject json = new JSONObject(responseData); it jumps to return null;, not return json; or catch(Exception e).
I don't know why, please help me with this

This occurs during step-by-step debugging, when you have multiple return points from a method.
When converting the java bytecode to dalvik, the return calls are merged (for optimization reasons?), and when you debug the code, it may seem that you reach for the wrong one, or call multiple ones. That's not happening though, your code is correct, it's just how it appears when debugging.
You can see this post for more reference

try this code
private JSONObject test() {
try {
String responseData = "{\"m_tani\":[{\"tani_cd\":\"02\",\"tani_nm\":\"cs\"},{\"tani_cd\":\"03\",\"tani_nm\":\"pc\"}]}";
Log.i("Json", responseData.toString());
JSONObject json = new JSONObject(responseData);
return json;
} catch (JSONException e) {
e.printStackTrace();
Log.i("Json", "exception");
return null;
}
}

Related

How to get JSONObject without JSONArray

I have such a JSON: https://paste.ubuntu.com/p/HkTK9xTzNx/
How do I get a "imdb_id" String (line 14). There is no array which contains that value,it's not in square branches,so I don't know how to get it.
Solution as per your need:
try {
imdbLink = response.getString("imdb_id");
} catch (JSONException e) {
e.printStackTrace();
}
A standard solution:
String json = "{\"imdb_id\":\"str12345\"}"; // your json response from network call/local file
JSONObject jsonObject;
try {
jsonObject = new JSONObject(json);
String id = jsonObject.getString("imdb_id");
} catch (Exception e) {
e.printStackTrace();
}

"HttpDeleteWithBody" isn't deleted from Database

I'm trying to call to my API sending a JSON to delete a product from my DB; however, it doesn't delete anything.
The response of the JSON is "true," and it doesn't give to me any error; even so, when I make a query on my DB, the product is still there.
I've created a class called HttpDeleteWithBody that looks like:
class HttpDeleteWithBody extends HttpEntityEnclosingRequestBase {
public static final String METHOD_NAME = "DELETE";
public String getMethod() { return METHOD_NAME; }
public HttpDeleteWithBody(final String uri) {
super();
setURI(URI.create(uri));
}
public HttpDeleteWithBody(final URI uri) {
super();
setURI(uri);
}
public HttpDeleteWithBody() { super(); }
}
And then on my doInBackGround of my Fragment, I do this:
boolean resul = true;
try {
JSONObject usuari = new JSONObject();
try {
usuari.put("idProducte", params[0]);
usuari.put("idusuari", params[1]);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
HttpEntity entity = new StringEntity(usuari.toString());
HttpClient httpClient = new DefaultHttpClient();
HttpDeleteWithBody httpDeleteWithBody = new HttpDeleteWithBody(getResources().getString(R.string.IPAPI) + "produsuaris/produsuari");
httpDeleteWithBody.setEntity(entity);
HttpResponse response = httpClient.execute(httpDeleteWithBody);
Log.d("Response ---------->", response.getStatusLine().toString());
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} catch (Exception ex) {
Log.e("ServicioRest", "Error!", ex);
}
return resul;
Furthermore, I've tried to do this:
HttpDeleteWithBody delete = new HttpDeleteWithBody(getResources().getString(R.string.IPAPI) + "produsuaris/produsuari");
StringEntity se = new StringEntity(usuari.toString(), HTTP.UTF_8);
se.setContentType("application/json");
delete.setEntity(se);
however, it doesn't work... the log says:
D/Response ---------->﹕ HTTP/1.1 200 OK
This is how I call the method:
JSONObject deleteproduct = new JSONObject();
try {
deleteproduct.put("idProducte", String.valueOf(IDPROD));
deleteproduct.put("idusuari", String.valueOf(IDUSU));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.i("Json test per afegir prod --> ", deleteproduct.toString());
TareaWSInsertar tarea = new TareaWSInsertar();
tarea.execute(String.valueOf(IDPROD), String.valueOf(IDUSU));
I've added on my Google Chrome a plug-in called "PostMan" and when I try to do this by this way, it's deleting correctly...
What I'm doing wrong?
EDIT
I tried to use cURL, and this is the result:
It is returning me false, when I put the same JSON as PostMan; nevertheless, if I put the same JSON on PostMan, it works fine.
EDIT 2
I implemented ion library and I did it like :
JSONObject usuari = new JSONObject();
try {
usuari.put("idProducte", params[0]);
usuari.put("idusuari", params[1]);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
String url = getResources().getString(R.string.IPAPI) + "produsuaris/produsuari";
Log.d("CURL", "curl -X DELETE -d '" + usuari.toString() + "' " + url);
Builders.Any.F builder = Ion.with(getActivity().getApplicationContext())
.load(HttpDelete.METHOD_NAME, url)
.setTimeout(15000).setStringBody(usuari.toString());
String response = builder.toString();
Log.d("TEST", "Req response -->" + response);
}
catch (Exception ex){
resul = false;
}
And it still returning that it's OK, and don't delete anything.
This appears to be a server side issue, to be sure of this, do the following:
1) Add Ion as an dependency in your grandle.
compile 'com.koushikdutta.ion:ion:+'
2) Use the following snippen to perform your request:
JSONObject jsonObject = new JSONObject();
try{
for(BasicNameValuePair aNameValue : getParameters()){
jsonObject.put(aNameValue.getName(), aNameValue.getValue());
Log.d("TEST","parameter "+aNameValue.getName()+": "+aNameValue.getValue());
}
jsonObject.put("time_zone", Util.timeZone());
Log.d("TEST","parameter time_zone:"+Util.timeZone());
}catch(Exception e){
//
}
Log.d("CURL", "curl -X DELETE -d '"+jsonObject.toString()+"' "+getUrl());
Builders.Any.F builder = Ion.with(getContext())
.load(HttpDelete.METHOD_NAME, getUrl())
.setTimeout(BuildConfig.HttpClientMaxTimeout).setStringBody(jsonObject.toString());
String response = builder.asString().get();
Util.checkThreadUiException();
Log.d("TEST","-->"+ response);
There's no much rocket science, this is the code that I used in an app, in that method I received the parameters to send as a json, as a BasicNameValuePair collection. You can change that and directly set your json. I'm 100% porcent sure that this request will fail, because this is a server side issue.
UPDATE
JSONObject usuari = new JSONObject();
try {
usuari.put("idProducte", params[0]);
usuari.put("idusuari", params[1]);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String url = getResources().getString(R.string.IPAPI) + "produsuaris/produsuari";
Log.d("CURL", "curl -X DELETE -d '"+usuari.toString()+"' "+url);
Builders.Any.F builder = Ion.with(getContext())
.load(HttpDelete.METHOD_NAME, url)
.setTimeout(BuildConfig.HttpClientMaxTimeout).setStringBody(usuari.toString());
String response = builder.asString().get();
Log.d("TEST","Req response -->"+ response)
UPDATE
Try this, perform this request through curl and let me know the result:
curl --http1.0 -X DELETE -d '{"idusuari":121,"idProducte":15}' 192.168.1.46/ServicioWebRest/api/produsuaris/produsuari
Doing this you're telling to curl to send the request through http 1.0, chunked responses are only supported by http 1.1, if there's an error in the chunk encoding, this should tell you.
Also take a look to this issue that I submitted to Ion long ago. I think that the problem that I was having that time, and your current problem are alike, maybe some of the tips there will help. Specially the part about the addHeader("Connection", "close").
Would look like this:
Builders.Any.F builder = Ion.with(getContext())
.addHeader("Connection", "close")
.load(HttpDelete.METHOD_NAME, getUrl())
.setTimeout(BuildConfig.HttpClientMaxTimeout).setStringBody(jsonObject.toString());
Finally I solved the problem, what I've done is change the HttpDelete method on my API, and instead of send a JSON, I send parameters (like a HttpGet) and now my code is like :
boolean resul = true;
HttpClient httpClient = new DefaultHttpClient();
String id____USER = params[0];
String id____PROD = params[1];
HttpDelete del =
new HttpDelete(getResources().getString(R.string.IPAPI) + "produsuaris/produsuari?idProd=" + Integer.parseInt(id____PROD)+"&idUs="+Integer.parseInt(id____USER));
del.setHeader("content-type", "application/json");
try
{
HttpResponse resp = httpClient.execute(del);
String respStr = EntityUtils.toString(resp.getEntity());
if(!respStr.equals("true"))
resul = false;
}
catch(Exception ex)
{
Log.e("ServicioRest","Error!", ex);
resul = false;
}
return resul;
This is how I call this AsyncMethod
TareaWSInsertar tarea = new TareaWSInsertar();
tarea.execute(String.valueOf(IDUSU),String.valueOf(IDPROD));
This work to me, I know it's not the best solution, but I've no much time, also I tried three solutions and noone didn't work.
Feel free to post a correct answer if you know what I was doing wrong.

How to handle null response for json array in android

I got a json response as
{
"tasks": null,
"projects": null
}
how to check if the array has null values and handle the case??
Thanks:)
Try this,
jsonObject.isNull("field-name")
Reference: JSON null handling and this.
Try This
=============
try {
String url;
JSONObject JsonData = new JSONObject("YOUR FULL JSONSTRING");
JSONArray webData = JsonData.getJSONArray("YOUR ROOT NAME OF YOUR JSON RESPONSE");
for(int i=0;i<webData.length();i++)
{
JSONObject TeampObj = webData.getJSONObject(i);
if(TeampObj.getString("tasks").trim().length()>0)
{
//store data in arrylist or string array
}
if(TeampObj.getString("projects").trim().length()>0)
{
//store data in arrylist or string array
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Try..
public boolean isNull (String name)
Added in API level 1
Returns true if this object has no mapping for name or if it has a mapping whose value is NULL.
use try ... catch to handle the exception:
Try{
// parsing data
}catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}

Parsing asmx returned JSON on Android

I have an ASP.Net 3.5 Webservice (asmx) that returns what appears to be valid JSON. I have validated the returned JSON using an online validator (JSONLint . com) and it says it is valid. I can not figure out how to parse this string.
{
"d": "{\"returnType\":\"authToken\",\"returnData\":\"b1ec28b8-3fca-427a-bbce-8802fb95d94b\"}"
}
Below is my code.
public static JSONObject DotNetJSONResponse(String raw) throws Exception {
JSONObject joRaw;
try {
joRaw = new JSONObject(raw);
JSONObject joD = joRaw.getJSONObject("d");
return joD;
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
try this way
public static JSONObject DotNetJSONResponse(String raw) throws Exception {
JSONObject joRaw;
try {
joRaw = new JSONObject(raw);
String str1 = joRaw.getString("d");
JSONObject joD = new JSONObject(str1);
return joD;
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
try this one. In your sample response, d is a an attribute, not a JSONObject. So have to parse the string first, then convert the d string as a JSONObject.
public static JSONObject DotNetJSONResponse(String raw) throws Exception {
JSONObject joRaw;
try {
joRaw = new JSONObject(raw);
String t=joRaw.getString("d");
System.out.println(t); \\< ----------
JSONObject joD = new JSONObject(t);
return joD;
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}

problems converting string to JSON

Im creating this JSONObject in javascript.
var jsonBack = {id:userID,"dateToday":today, dateYesterday:yesterday,
wbsArrayToday:[{wbs:"13232323"}, {wbs:"13232324"}, {wbs:"13232325"}],
wbsArrayYesterday:[{wbs:"13232333"}, {wbs:"13232334"}, {wbs:"13232335"}]};
Then i call this in my android application.
JSONObject jsonObj = null;
// Henter response data fra server vha. httpResponse
HttpEntity entity1 = response.getEntity();
if (entity1 != null) {
InputStream is = null;
try {
is = entity1.getContent();
// convert stream to string
String result = Converter.convertStreamToString(is);
//Remove []
//if(result.startsWith("["))
// result = result.substring(1, result.length()-1);
// Create JSON Object
jsonObj = new JSONObject(result);
} catch (IllegalStateException e) {
e.printStackTrace();
throw new HttpNodeClientException("HttpNodeClientException/IllegalStateException - createResponse():" + e.getMessage());
} catch (IOException e) {
e.printStackTrace();
throw new HttpNodeClientException("HttpNodeClientException/IOException - createResponse():" + e.getMessage());
} catch (JSONException e) {
e.printStackTrace();
throw new HttpNodeClientException("HttpNodeClientException/JSONException - createResponse():" + e.getMessage());
} catch (ConverterException e){
e.printStackTrace();
throw new HttpNodeClientException("HttpNodeClientException/ConverterException - createResponse():" + e.getMessage());
}
And i get an JSONException. Did i design the JSON wrong?
Heres the exception:
08-14 16:14:18.522: I/LoginActivity(418): HttpNodeClientException/JSONException - createResponse
():Value {"id":"11111111","dateToday":"14082012","dateYesterday":"13082012","wbsArrayToday":
[{"wbs":"13232323"},{"wbs":"13232324"},{"wbs":"13232325"}],"wbsArrayYesterday":
[{"wbs":"13232333"},{"wbs":"13232334"},{"wbs":"13232335"}]} of type java.lang.String cannot be
converted to JSONObject
Use the JSONTokener class instead. It parses a string and return a JSON object.
the only line you need to fix is this one:
jsonObj = new JSONObject(result);
into this one:
jsonObj = new JSONObject(new JSONTokener(result));

Categories

Resources