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.
Related
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();
}
I want to ask if there's some way to split data obtained from server by some unique separator.
Here is an example:
I use AsyncTask to send data to server and then I use echo command for sending those back to my application and in onPostExecute I split these data to needed result.
So let's say, that I want to get from server data for Name and Surname, so echo command on server will look like this: echo $name."&".$surname;
And then in onPostExecute I will split this data by "&" separator, but problem occurs when user writes to name or surname my separator "&" which I am using for split.
How can I avoid this issue?
Look into using JSON. It's a life saver for sending data.
Android has native JSON support using a JSONObject.
Documentation
It essentially provides a formatter and parser for information placed within the object that are then accessible via keywords.
To write a json:
public String writeJSON() {
JSONObject object = new JSONObject();
try {
object.put("name", "John");
object.put("surname", "Doe");
return object.toString();
} catch (JSONException e) {
e.printStackTrace();
return null;
}
}
This will return a string that looks like:
{"name":"John","surname":"Doe"}
To read:
public void readJSON(String jsonString){
try {
JSONObject object = new JSONObject(jsonString);
String name = object.getString("name");
String surname = object.getString("surname");
} catch (JSONException e){
e.printStackTrace();
}
}
You need to escape the character you are using to separate the different entries in the content you are transmitting [1]. For example:
My\&FirstName&MySecondName (In this case \ is used as escape character)
However, you don't need to reinvent all this stuff. There are several formats that you could use to transmit your data:
json
xml
csv
[1] https://en.wikipedia.org/wiki/Escape_character
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()));
So, I am trying to retrieve JSON data from a webservice. It usually works. It doesn't work, however, if the value of a certain variable has double quotations as part of its content. For example, if I am parsing this data:
{"ID":"1057","PlaceTitle":"Place 1","PlaceDetails":"George Bush once said "This is the best dang place in the world""}
I get an error on "George bush... because it is trying to detect it as a variable because of the quotes, I believe. This exception is thrown:
org.json.JSONException: Unterminated object at character 1418 of
So what I want to do is "if this exception is thrown, treat it as content within PlaceDetails, and continue on." Any idea how I can accomplish this?
Code:
try {
JSONArray jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
final JSONObject json = jArray.getJSONObject(i);
try {
arrayOfLocationss.add(new Location(context,
json.getInt("ID") json
.getString("PlaceTitle"), json
.getString("PlaceDetails"));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
You need to fix the webservice so it returns properly formatted JSON. Quotes inside of strings need to be escaped with a backslash:
{"ID":"1057","PlaceTitle":"Place 1","PlaceDetails":"George Bush once said \"This is the best dang place in the world\""}
Why dont you escape all double quotes when you use getString? Try something like
arrayOfLocationss.add(new Location(context,
json.getInt("ID") json
.getString("PlaceTitle").toString().replaceAll("\"", "\\\""),
json.getString("PlaceDetails").toString().replaceAll("\"", "\\\""));
I need to pass HTTP JSON request as array values as "Id":["13","14","15","17","27","29" ] in android.How could i do that?I tried like this "Id": { "\"13\"".. }
Thanks.
My answer:
Finally i got it.
for (String sstring : new String[] { "1","2" }) {
Carray.put(sstring);
}
Thanks for the support.
JSONObject Root = new JSONObject();String Data1 = "[13,14,15,17,27,29]";
try
{
Root.put("Id", Data1);Log.e("try",Root.toString());
}
catch (JSONException e)
{
e.printStackTrace();
}
Using Above Code You Get This Type Of Output//OutPut :- {"Id":["13","14","13","15","27","29"]}