Can't get a string from nested downloaded JSON [duplicate] - android

This question already has answers here:
How do I parse JSON in Android? [duplicate]
(3 answers)
Closed 5 years ago.
I'm getting a JSON from the server:
JSONObject vkjson = response.json;
I have tried to make it a string and check via LogCat to make sure it works - and yeah, it 100% works.
But it is nested:
{"response":{"first_name":"...","last_name":"..."} }
I have tried to do this:
String result = vkjson.getJSONObject("response").getString("first_name");
But IDE doesn't like the getJSONObject part and underlines it. IDE says:
Unhandled exception in org.json.JSONException
What's wrong? Is it because the JSON is loading from the server or the code is incorrect?
Thank you in advance.

Unhandled exception in org.json.JSONException
Mean that the method can throw a JSONException and you have to handle it.
So you have to:
try {
String result = vkjson.getJSONObject("response").getString("first_name");
} catch (JSONException exception){
//Handle exception here
}

There's nothing wrong with your code other than not handling the JSONException which is potentially thrown (i.e. what would happen if there isn't an object called "response").
You need to look at exception handling and wrap this code in a try .. catch block or otherwise deal with the exception.
Java exception handling

Do this-:
try
{
JSONObject vkjson = response.json;
//More code related to json
}
catch(JsonException e)
{
e.printStackTrace();
}

JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(responseString);
if(jsonObject != null)
{
if (jsonObject.has("response")) {
JSONObject responseObject = jsonObject.getJSONObject("response");
String firstName = responseObject.getString("first_name");
Log.d("Tag",firstName);
}
}
} catch (JSONException e) {
e.printStackTrace();
}

Related

android:json object giving error

I want to send an JSONObject using retrofit 2 to server and i am sending this kind of json object :
{"Order Summary":
"[
{
\ "ProductName\":\"Wine\",
\"ProductPrice\":\"500\",
\"ProductQuantity\":\"2\",
\"ProductCost\":\"1000\",
\"SellerId\":\"2\"
},
{
\"ProductName\":\"Whiskey\",
\"ProductPrice\":\"1000\",
\"ProductQuantity\":\"1\",
\"ProductCost\":\"1000\",
\"SellerId\":\"1\"
}
]"}
due to which i'm unable to parse the json object
and this is the source code iam using :-
private void loadCart()
{
Cursor cursor = dbHelper.getCarProducts();
cursor.moveToFirst();
do {
JSONObject product = new JSONObject();
try {
product.put("Sellerid",cursor.getString(cursor.getColumnIndex("_Sellerid")));
product.put("ProductCost",cursor.getString(cursor.getColumnIndex("_Cost")));
product.put("ProductQuantity",cursor.getString(cursor.getColumnIndex("_Quantity")));
product.put("ProductPrice",cursor.getString(cursor.getColumnIndex("_Price")));
product.put("ProductName",cursor.getString(cursor.getColumnIndex("_Name")));
userCart.put(product);
} catch (JSONException e) {
e.printStackTrace();
}
}while(cursor.moveToNext());
Cart = new JSONObject();
try
{
Cart.put("OrderSummary",userCart.toString());
}
catch (Exception ex)
{}}
could someone tell me how to rectify this error ?
Here is your mistake
Cart.put("OrderSummary", userCart.toString());
You get pure JSON Array but why are you converting it to String?
Use,
Cart.put("OrderSummary", userCart); // remove .toString()
Edit
By checking your server side code, I think the problem is in index.php file (I'm not expert in PHP)
$requestedData = $response->getBody();
Instead of $response you should use $request object. In order to fix that refer this StackOverflow thread or refer this official doc of Slim Framework.
And to send JSON response from Slim Framework to refer this StackOverflow thread.
Note: While declaring Java variables/objects try to respect Java varibales/method naming conventions. Instead of Cart use cart, this eliminates ambiguity.

Android - JSON No value for 1 - but there is using Log

I'm stuck at trying to get a simple string from a JsonObject.
Here is the basic code. result is a JsonObject returned from an Asynctask. I've done dozens of the same way, and here it doesn't work.
Response:{"status":200}
Error: An error is thrown saying "No value for 1"
When I Log the content of the JsonObject, I get this: 200, which is what I want. For which reason could this return null when there is a value?
Edit if I use the result.has("status"); true is returned. I don't understand.
Log.e("TAG", result.get("status").toString());
try{
String status = result.getString("status");
} catch (Exception e){
e.getMessage();
}
You are getting int value in the object and you are holding in string which causes the error
You are getting int value in status
{
"status":200
}
if it is like
{
"status":"200"
}
Your code works perfectly.
Try this
Log.e("TAG", result.get("status").toString());
try{
int status = result.getInt("status");
} catch (Exception e){
e.getMessage();
}

JSONParser doesn't work in Android

This type of JSON Object is coming to my Android device :
{"Successful":true,"Value":{"Materials":[{"MaterialID":999999,"Type":1,"StockNo":1,"Weight":1}]}}
I'm trying to parse that like this :
public String parseMaterial(JSONObject object){
try{
JSONArray objectArray = object.getJSONArray("Value");
}
catch(JSONException e){
Log.d("Jsonparser=>error", e.getMessage());
}
}
What I get in Logcat is :
D/Jsonparser=>error: Value:{"Materials":[{"MaterialID":999999,"Type":1,"StockNo":1,"Weight":1}]}
What am I doing wrong here? Why does the program fall in to catch block? Thanks.
Cause Value is not a Json Array

Weird JSON encoding issue on Android 4.1.2

I have an issue on Android 4.1.2 where a JSON object given to us by our REST API gets encoded weirdly when sending back.
This is the snippet of json I'm getting:
"cost":{
"amount": 0,
"currency": "GBP"
}
I'm wanting to pretty much just pass this particular snippet back the same way (modifying other parts of the json), but this is what I get on Android 4.1.2:
"cost":"{amount=0, currency=GBP}"
The function I believe is causing this weird encoding is here:
private StringEntity getEntityForRequest(final Payment payment, final PaymentDelegate delegate) {
JSONObject json = new JSONObject();
MyApplication.getContext().addApplicationInformationToJSONObject(json);
StringEntity entity = null;
try {
entity = new StringEntity(json.toString(), "UTF-8");
} catch (UnsupportedEncodingException e1) {
payment.markAsFailed("Reservation failed, data returned not expected.");
save(payment);
if (delegate != null) {
delegate.onFailure(new MyError(MyError.DEFAULT_STATUS, MyError.DEFAULT_TYPE, "Payment error", "Error during reservation"));
}
}
return entity;
}
This is the addApplicationIformationToJSONObject function:
/**
* Adds system information to a JSON object.
*/
public void addApplicationInformationToJSONObject(JSONObject json) {
try {
try {
json.put("app_version", getPackageManager().getPackageInfo(getPackageName(), 0).versionName);
} catch (NameNotFoundException e) {
json.put("app_version", "Unknown");
}
json.put("device", getDeviceName());
json.put("os_type", "android");
json.put("os_version", String.format("%d", Build.VERSION.SDK_INT));
json.put("device_id", Secure.getString(getContext().getContentResolver(), Secure.ANDROID_ID));
} catch (JSONException e) {
MyLog.e("MyApplication", "Error when adding system information to JSON");
}
}
What's causing this weird encoding?
How can I modify the code to avoid issues like this?
Found a solution. It seems older version interprets that cost snippet as a string rather than a JSONObject. Doing this seems to solve the issue:
ticketObject.remove("cost");
ticketObject.put("cost", new JSONObject(getCost()));

Type mismatch: cannot convert from Object to JSONObject

I'm relatively new to Android development and am writing my first REST-based app. I've opted to use the Android Asynchronous HTTP Client to make things a bit easier. I'm currently just running through the main "Recommended Usage" section on that link, essentially just creating a basic static HTTP client. I'm following the code given, but changing it around to refer to a different API. Here's the code in question:
public void getFactualResults() throws JSONException {
FactualRestClient.get("q=Coffee,Los Angeles", null, new JsonHttpResponseHandler() {
#Override
public void onSuccess(JSONArray venues) {
// Pull out the first restaurant from the returned search results
JSONObject firstVenue = venues.get(0);
String venueName = firstVenue.getString("name");
// Do something with the response
System.out.println(venueName);
}
});
}
The String venueName = firstVenue.getString("name"); line is currently throwing an error in Eclipse: "Type mismatch: cannot convert from Object to JSONObject". Why is this error occurring? I searched other threads which led me to try using getJSONObject(0) instead of get(0) but that led to further errors and Eclipse suggesting using try/catch. I haven't changed any of the code on the tutorial, save for the variable names and URL. Any thoughts/tips/advice?
Thanks so much.
EDIT:
Here is the onSuccess method, modified to include the try/catch blocks suggested. Eclipse now shows the "local variable may not have been initialized" for firstVenue here: venueName = firstVenue.getString("name"); and for venueName here: System.out.println(venueName); Even if I initialize String venueName; directly after JSONObject firstVenue; I still get the same error. Any help in resolving these would be greatly appreciated!
public void onSuccess(JSONArray venues) {
// Pull out the first restaurant from the returned search results
JSONObject firstVenue;
try {
firstVenue = venues.getJSONObject(0);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String venueName;
try {
venueName = firstVenue.getString("name");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Do something with the response
System.out.println(venueName);
}
You can try to convert object you are getting from querying to String and then use
final JSONObject jsonObject = new JSONObject(stringresult);
I was getting same error earlier, it worked for me.
Yes, you should be using getJSONObject to ensure that the value you obtain is a JSON object. And yes, you should catch the possible JSONException which is thrown if that index in the array doesn't exist, or does not contain an object.
It'll look something like this:
JSONObject firstVenue;
try {
firstVenue = venues.get(0);
} catch (JSONException e) {
// error handling
}
convert obj to json Object:
Object obj = JSONValue.parse(inputParam);
JSONObject jsonObject = (JSONObject) obj;
The solution provided by Shail Adi only worked for me by setting the initial values of firstVenue and venueName to null. Here's my code:
JSONObject firstVenue = null;
try {
firstVenue = (JSONObject)venues.get(0);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String venueName = null;
try {
venueName = firstVenue.getString("name");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Do something with the response
System.out.println(venueName);

Categories

Resources