Get jsonvalue without a name - java

i'm struggling with a JSONObject. I allready returned some json and converted it succesfully to objects and list of objects. My now i'm stuck.
This is the JSONObject i'm getting:
{"Result":true,"Messages":["Goe bezig!"]}
I'm able to get the Messages, but i can't seem to get the boolean in Result. Can somebody explain how to get it plz?
Here is the code:
public boolean Convert(JSONObject json) {
try
{
return json.getBoolean("Result");
}
catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
}

This worked fine for me, although it's pretty vague your question.
String jsonString = "{\"Result\":true,\"Messages\":[\"Goe bezig!\"]}";
JSONObject jsonObject = new JSONObject(jsonString);
boolean result = (Boolean) jsonObject.get("Result");
System.out.println(result);
You might want to catch at the end of your method Exception as well:
try {
return json.getBoolean("Result");
} catch (JSONException e) {
e.printStackTrace(); // replace these with `Log` statement
return false;
} catch (Exception e) {
e.printStackTrace(); // replace these with `Log` statement
return false;
}

Related

How to create a complex Json structure manually in android without using API?

I would like to create a Json structure manually using JsonObject and JsonArrays like the below:
{
"data":[
{
"company_name":"xyz",
"Amount":"$2000",
"Duplicate_amount":"$500"
},
{
"company_name":"abc",
"Amount":"$5000"
},
{
"company_name":"zzz",
"Amount":"$2500",
"Duplicate_amount":"$1000"
}
]
}
The Json above is to be generated based on a checking done on an Arraylist. For example: Arraylist [xyz,abc,zzz,xyz,hhh,zzz]. Now I want to check, if the arraylist contains duplicate elements i.e here "xyz" and "zzz" then in the Json structure, the Duplicate_amount Json object to be added in the Json. Else if no duplicate present then only "company_name" and "amount" to be formed. The whole json format to be formed in this way.
How to do it? I have the logic for finding duplicate elements. But I cannot seem to find the logic for forming the above json based on the checking.
Thank you
Updates
So far I have tried this with checking. But the below code doesn't work and is not forming the appropriate json. What is the solution ?:
JSONObject root_jsonObj = new JSONObject();
JSONArray jsonArr = new JSONArray();
JSONObject sub_jsonobj= new JSONObject();
Object[] st = AppData.customer_arr.toArray();
for (Object s : st) {
//The if-else is the duplicate checking part here
if (AppData.customer_arr.indexOf(s) != AppData.customer_arr.lastIndexOf(s)) {
try {
sub_jsonobj.put("name",AppData.customer_arr.get(counter));
sub_jsonobj.put("dup_amount",AppData.amt_arr.get(counter));
} catch (Exception e) {
e.printStackTrace();
}
}
else{
try {
sub_jsonobj.put("name",AppData.customer_arr.get(counter));
sub_jsonobj.put("amount",AppData.amt_arr.get(counter));
} catch (Exception e) {
e.printStackTrace();
}
}
jsonArr.put(sub_jsonobj);
counter++;
}
try {
root_jsonObj.put("data", jsonArr);
} catch (Exception e) {
e.printStackTrace();
}
You can use this one.
JSONObject obj1 = new JSONObject();
try {
obj1.put("company_name", "xyz");
obj1.put("Amount", "$2000");
obj1.put("Duplicate_amount", "$500");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JSONObject obj2 = new JSONObject();
try {
obj2.put("company_name", "xyz");
obj2.put("Amount", "$2000");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JSONArray jsonArray = new JSONArray();
jsonArray.put(obj1);
jsonArray.put(obj2);
JSONObject dataObj = new JSONObject();
dataObj.put("Data", jsonArray);
String jsonStr = dataObj.toString();
System.out.println("jsonString: "+jsonStr);

why is try catch required for every field in json parsing

I see an old method from a colleague of deserializing json object in java where the json is taken as string deserialized and passed the values in an array. What I dont understand about this code is why for every field try and catch method is added and why can't we have a single try and catch because all catch do the same thing of catching the json exception and assigning responseArray[0] to value 1.
Here is the code:
String[] responseArray = new String[4];
Arrays.fill(responseArray, "");
try {
final JSONObject response1 = new JSONObject(response);
try{
responseArray[0] = response1.getJSONObject("body")
.getJSONObject("responseStatus").getString("estado");
}
catch (JSONException e) {
responseArray[0] = "1";
e.printStackTrace();
}
if(!responseArray[0].equalsIgnoreCase("0")){
try{
responseArray[1] = response1.getJSONObject("body")
.getJSONObject("responseStatus")
.getString("codigoRespuesta");
}
catch (JSONException e) {
responseArray[0] = "1";
e.printStackTrace();
}
try{
responseArray[2] = response1.getJSONObject("body")
.getJSONObject("responseStatus")
.getString("descripcionRespuesta");
}
catch (JSONException e) {
responseArray[0] = "1";
e.printStackTrace();
}
}
try{
responseArray[3] = response1.getJSONObject("body")
.getJSONObject("responseData").getLong("esValido")+"";
}
catch (JSONException e) {
responseArray[0] = "1";
e.printStackTrace();
}
} catch (JSONException e) {
responseArray[0] = "1";
e.printStackTrace();
}
return responseArray;
There is no explicit need to add try and catch blocks to every ".getJSONObject" methods.
There are two ways by which you can use exception handling.
1. try-catch blocks. Single try & catch block would work fine as well.
2. Let the method throws JSONException as a replacement to try and catch blocks.
Checked exceptions (like the one in your case) are checked at compile time, and so you need to handle them using either of the two ways
Exception handling reference link

Android Java JSON Unhandled Exception

I have a method which needs to return a JSONObject:
public JSONObject getDayJson(Date date) {
...
a few lines of code
...
return new JSONObject("..");
}
However this gives me an error as I need to catch any exceptions which may occur as a result of instantiating the JSONObject:
public JSONObject getDayJson(Date date) {
try {
...
a few lines of code
...
return new JSONObject("..");
} catch (Exception e) {
// need a return statement here!
}
}
This creates another error as in the catch block I am not returning the correct object type which is a JSONObject. If I do instantiate another JSONObject in the catch I need to nest another catch statement?!
You should better think what you want to do if an exception happens, but one option is to force a non exception calling constructor.
public JSONObject getDayJson(Date date) {
try {
...
a few lines of code
...
return new JSONObject("..");
} catch (Exception e) {
// doesn't throw another exception
return new JSONObject(new HashMap());
}
}

Return statement before a catch statement

I've added a return statement to my AsncTask and yet I still get an error telling me to add one. The only snippet of code that stops this Syntax error is adding a return statement after the catch statement, but that's counter productive and doesn't address the needs of the program and I can't access the Strings I need to ( I need to check if the return OuputStream is equal to true.
Code:
#Override
protected Boolean doInBackground(String... userandpass) { //I still get an error telling me to add a return statement
// TODO Auto-generated method stub
URL url;
try {
url = new URL("http://127.0.0.1:1337");
HttpURLConnection URLconnection = (HttpURLConnection) url.openConnection();
URLconnection.setDoOutput(true);
URLconnection.setChunkedStreamingMode(0);
//output stream
OutputStream out = new BufferedOutputStream(URLconnection.getOutputStream());
writestream(out, userandpass);
//buffered server response
InputStream in = new BufferedInputStream(URLconnection.getInputStream());
String result = readstream(in);
Log.e(result, result);
// check we haven't been redirected (Hotel Wifi, for example).
checkrediect(URLconnection, url);
Boolean result_true = checkresult(result);
if(result_true) {
return true;
} else {
return false;
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
but that's counter productive and doesn't address the needs of the program
Well what are the "needs of the program"? What do you want the result to be if an IOException is thrown? It must be true, false, or an exception - at the moment, it's none of those.
I'd recommend that most of the time, you just let exceptions bubble up... can you actually proceed as if nothing had gone wrong in the case of an IOException?
As a side-note, this is ugly:
if(result_true) {
return true;
} else {
return false;
}
Just use:
return checkresult(result);
(And ideally rename various methods and variables to follow Java naming conventions.)
I'd also suggest changing it to return boolean rather than Booelean.
You have a branch of your catch statement that neither returns a value nor throws an exception.
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
That block there needs to have some form of code that will return something, otherwise the method will not be able to function properly.
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
You have to add a return statement with in the method block.
Do it like this....
protected Boolean doInBackground(String... userandpass) {
boolean isOk = false;
// Your code
if(result_true) {
isOk = true;
} else {
isOk = false;
}
return isOk;
}
You must had a return statement in the catch (IOException e) block. The compiler cannot know what to return when you catch the IOException.
You have 2 choices, return something (false), or rethrow the exception.

java try catch and return

I have a small function in java that does a HTTP POST, and returns a JSON Object. This function return the JSON Object.
public JSONObject send_data(ArrayList<NameValuePair> params){
JSONObject response;
try {
response = new JSONObject(CustomHttpClient.executeHttpPost(URL, params).toString());
return response;
} catch(Exception e) {
// do smthng
}
}
This shows me an error that the function must return a JSONObject. how do i make it work? I cant send a JSONObject when there is an error, can I? It would be useless to send a blank jsonobject
This is because you are only returning a JSONObject if everything goes smoothly. However, if an exception gets thrown, you will enter the catch block and not return anything from the function.
You need to either
Return something in the catch block. For example:
//...
catch(Exception e) {
return null;
}
//...
Return something after the catch block. For example:
//...
catch (Exception e) {
//You should probably at least log a message here but we'll ignore that for brevity.
}
return null;
Throw an exception out of the method (if you choose this option, you will need to add throws to the declaration of send_data).
public JSONObject send_data(ArrayList<NameValuePair> params) throws Exception {
return new JSONObject(CustomHttpClient.executeHttpPost(URL, params).toString());
}
You could change it to this:
public JSONObject send_data(ArrayList<NameValuePair> params){
JSONObject response = null;
try {
response = new JSONObject(CustomHttpClient.executeHttpPost(URL, params).toString());
} catch(Exception e) {
// do smthng
}
return response;
}
There's a path through the function that doesn't return anything; the compiler doesn't like that.
You can change this to
catch(Exception e) {
// do smthng
return null; <-- added line
}
or put the return null (or some reasonable default value) after the exception block.
It's reasonble to return 'something' even in an error condition.
Look at JSend for a way to standardize your responses - http://labs.omniti.com/labs/jsend
In my opinion it's easiest to return an error json object and handle that on the client side then to solely rely on HTTP error codes since not all frameworks deal with those as well as they could.
The send_data() method should throw an exception so that the code calling send_data() has control over how it wants to handle the exception.
public JSONObject send_data(ArrayList<NameValuePair> params) throws Exception {
JSONObject response = new JSONObject(CustomHttpClient.executeHttpPost(URL, params).toString());
return response;
}
public void someOtherMethod(){
try{
JSONObject response = sendData(...);
//...
} catch (Exception e){
//do something like print an error message
System.out.println("Error sending request: " + e.getMessage());
}
}
I prefer one entry and one exit. Something like this seems reasonable to me:
public JSONObject send_data(ArrayList<NameValuePair> params)
{
JSONObject returnValue;
try
{
returnValue = new JSONObject(CustomHttpClient.executeHttpPost(URL, params).toString());
}
catch (Exception e)
{
returnValue = new JSONObject(); // empty json object .
// returnValue = null; // null if you like.
}
return returnValue;
}

Categories

Resources