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("\"", "\\\""));
Related
Hello ! I want to change the values in my json file called "etatButton.json" but I do not know how.
[
{
"bouton1":"on",
"bouton2":"on",
"bouton3":"on",
"bouton4":"off",
"bouton5":"on",
"bouton6":"on",
"bouton7":"on",
"bouton8":"on",
"bouton9":"off",
"bouton10":"off"
}
]
For example I want to change the value of "bouton1" from "on" to "off" after onClick event like this one :
public void writeJson(View view) {
// Write smth in json file
}
Thank you !
This code can get you started....
try {
JSONArray json = new JSONArray();
JSONObject jsonobject = new JSONObject();
jsonobject.put("k1", "v1");
jsonobject.put("k2", "v2");
json.put(jsonobject);
System.out.println(json);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
OUTPUT:
[{"k1":"v1","k2":"v2"}]
If you want to be able to change v1 or v2, just use variables
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.
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'm creating an array that has to be sent to an api. Part of the json has contact info. that must be sent like so:
"Dealer" : {
"email" : "mjones#fake - domain.com" ,
"firstName" : "Martin" ,
"lastName" : "Jones" ,
"phone" : " 5555554321 " ,
"company" : "JonesCo Golf" ,
"street" : "554 Elm Street" ,
"city" : "Springfield" ,
"stateProvince" : "Illinois" ,
"postalCode" : "62701"
}
My json (when using Log.d) shows like this:
"Dealer":
[
{
"email":"email#email.com",
"firstName":"John",
"lastName":"Doe",
"phone":"0987654321",
"company":"test",
"street":"123 Street",
"city":"myCity",
"stateProvince":"Xy",
"postalCode":"12345"
}
]
instead of being Dealer with 9 objects it returns as Dealer with 1 object that contains 9 objects. Of course, this won't parse correctly when I send it to the API.
I'm pulling my content from a shared preference and loading creating the JSONArray like this:
JSONObject dealer = new JSONObject();
try {
dealer.put("email", salesPerson.get("emailAddress"));
dealer.put("firstName", salesPerson.get("firstName"));
dealer.put("lastName", salesPerson.get("lastName"));
dealer.put("phone", salesPerson.get("mobilePhone"));
dealer.put("street", salesPerson.get("mailingAddress1"));
dealer.put("street2", salesPerson.get("mailingAddress2"));
dealer.put("city", salesPerson.get("city"));
dealer.put("stateProvince", salesPerson.get("state"));
dealer.put("postalCode", salesPerson.get("postalCode"));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.d("dealer", dealer.toString());
JSONArray dealerJSON = new JSONArray();
dealerJSON.put(dealer);
try {
emailDataObject.put("Dealer", dealerJSON);
} catch (JSONException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
I have a pretty extensive JSONArray to send to the API, and the JSON is being created with no errors. The square brackets are being added everywhere I add the JSONObject to a JSONArray it seems.
how can I prevent the additional square brackets from being added the the json?
To avoid backers do not add your object to an array, but it to the object directly. Here is an example.
JSONObject dealer = new JSONObject();
try {
dealer.put("email", salesPerson.get("emailAddress"));
dealer.put("firstName", salesPerson.get("firstName"));
dealer.put("lastName", salesPerson.get("lastName"));
dealer.put("phone", salesPerson.get("mobilePhone"));
dealer.put("street", salesPerson.get("mailingAddress1"));
dealer.put("street2", salesPerson.get("mailingAddress2"));
dealer.put("city", salesPerson.get("city"));
dealer.put("stateProvince", salesPerson.get("state"));
dealer.put("postalCode", salesPerson.get("postalCode"));
} catch (JSONException e) {
e.printStackTrace();
}
Log.d("dealer", dealer.toString());
try {
emailDataObject.put("Dealer", dealer);
} catch (JSONException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
I'm not really into Android, but I can give you some directives, and I can surely tell you that you are conceptually wrong about your JSONs
"Dealer":
{
"email":"email#email.com",
"firstName":"John",
"lastName":"Doe",
"phone":"0987654321",
"company":"test",
"street":"123 Street",
"city":"myCity",
"stateProvince":"Xy",
"postalCode":"12345"
}
This first example is not an array of JSON objects, but instead a single objects with many properties
"Dealer":
[
{
"email":"email#email.com",
"firstName":"John",
"lastName":"Doe",
"phone":"0987654321",
"company":"test",
"street":"123 Street",
"city":"myCity",
"stateProvince":"Xy",
"postalCode":"12345"
}
]
This one instead, is a real JSON array, formed by a single element, which is your previous object.
You have to rethink about the adding of the elements in your JSON object, and what is your real expected behavior
Edit:
I think that this line could be held responsible for your unwanted array creation:
JSONArray dealerJSON = new JSONArray();
You are creating an array with this code:
JSONArray dealerJSON = new JSONArray();
So don't so that.
Just do this:
emailDataObject.put("Dealer", dealer);
You don't need the dealerJSON step, because dealer is the JSONObject you want.
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);