Android gson.toJson() gives a result with escaped quotes (\") - java

I use Gson to serialize my object, but the result contains many '\"' which should be '"', like:
{"data":"{\"calldate\":\"2012-05-03 00:12:00\",\"id\":0,\"uid\":0,\"popdbid\":0
,\"mobilesqlid\":1336025277424,\"callstatus\":2,\"checkstatus\":0,\"resultstatus
\":0,\"sequence\":0,\"subbrandstatus\":0,\"subcategorystatus\":0,\"synstatus\":1
,\"targetstatus\":0,\"trackstatus\":0,\"isfrommobile\":0}","user":{"id":11,"ente
rprise_id":1}}
This is the code I use to serialize:
GsonBuilder builder=new GsonBuilder();
builder.setDateFormat("yyyy-MM-dd mm:hh:ss");
builder.excludeFieldsWithoutExposeAnnotation();
Gson gson=builder.create();
String gsonString = gson.toJson(callDayPlanning);
Any suggestion?

As #PhilippReichart stated, your callDayPlanning contains (probably) a String field named data that contains a Json string. This is confirmed by json.parser.online.fr:
.
There's nothing wrong to put a Json string as payload of another object but it will be escaped. But, if you want that data would be the serialization of another object (whose class is named DayPlanning maybe?) you have to change data type from String to your custom class.

Related

Does the StringBuffer change the order of JSON?

I'm using StringBuffer to get JSON from a URL.
This is the original JSON
[{"name":"Italy","topLevelDomain":[".it"],"alpha2Code":"IT","alpha3Code":"ITA","callingCodes":["39"],"capital":"Rome","altSpellings":["IT","Italian Republic","Repubblica italiana"],"region":"Europe","subregion":"Southern Europe","population":60665551,"latlng":[42.83333333,12.83333333],"demonym":"Italian","area":301336.0,"gini":36.0,"timezones":["UTC+01:00"],"borders":["AUT","FRA","SMR","SVN","CHE","VAT"],"nativeName":"Italia","numericCode":"380","currencies":[{"code":"EUR","name":"Euro","symbol":"€"}],"languages":[{"iso639_1":"it","iso639_2":"ita","name":"Italian","nativeName":"Italiano"}],"translations":{"de":"Italien","es":"Italia","fr":"Italie","ja":"イタリア","it":"Italia","br":"Itália","pt":"Itália","nl":"Italië","hr":"Italija","fa":"ایتالیا"},"flag":"https://restcountries.eu/data/ita.svg","regionalBlocs":[{"acronym":"EU","name":"European Union","otherAcronyms":[],"otherNames":[]}],"cioc":"ITA"}]
This is the JSON That I end up with once I convert it to a string from the response
[{"area":301336,"nativeName":"Italia","capital":"Rome","demonym":"Italian","flag":"https://restcountries.eu/data/ita.svg","alpha2Code":"IT","languages":[{"nativeName":"Italiano","iso639_2":"ita","name":"Italian","iso639_1":"it"}],"borders":["AUT","FRA","SMR","SVN","CHE","VAT"],"subregion":"Southern Europe","callingCodes":["39"],"regionalBlocs":[{"otherNames":[],"acronym":"EU","name":"European Union","otherAcronyms":[]}],"gini":36,"population":60665551,"numericCode":"380","alpha3Code":"ITA","topLevelDomain":[".it"],"timezones":["UTC+01:00"],"cioc":"ITA","translations":{"br":"Itália","de":"Italien","pt":"Itália","ja":"イタリア","hr":"Italija","it":"Italia","fa":"ایتالیا","fr":"Italie","es":"Italia","nl":"Italië"},"name":"Italy","altSpellings":["IT","Italian Republic","Repubblica italiana"],"region":"Europe","latlng":[42.83333333,12.83333333],"currencies":[{"symbol":"\u20ac","code":"EUR","name":"Euro"}]}]
This is my code for getting the JSON + Converting it.
JSONArray JSON = null;
//Reading Variables
BufferedReader r = new BufferedReader(new InputStreamReader(con.getInputStream()));
String input;
StringBuffer response = new StringBuffer();
//Adding response to StringBuffer
while((input = r.readLine()) != null) {
response.append(input);
}
//Stopping the reader
r.close();
System.out.println(response);
//Convert StringBuffer to JSON
JSON = new JSONArray(response.toString());
System.out.println(JSON);
return JSON;
Is there a way of preventing it from doing this?
It's not the StringBuffer but the JSONArray.
The order of elements in an array [] is maintained like the list ["AUT","FRA","SMR","SVN","CHE","VAT"] in both examples.
Anything as a name value pair surrounded by {} can be reordered like {"code":"EUR","name":"Euro","symbol":"€"} and {"symbol":"\u20ac","code":"EUR","name":"Euro"}.
To prevent this, you can keep it as a String or create your own object and define the toString method.
Your question is similar to Keep the order of the JSON keys during JSON conversion to CSV.
It is not StringBuffer doing this. It is the JSON implementation itself.
For a start, according to all of the JSON specifications that I have seen, the order of the attributes of a JSON object are not significant. A JSON parser is not expected to preserve the attribute order, and neither is the in memory representation of a JSON object. So, for example, a typical in-memory representation of a JSON object uses a HashMap to hold the attribute names and values.
So my first piece of advice to you would be to change your application so that the order of the JSON attributes doesn't matter. If you design a JSON API where attribute order matters, then your API will be problematic.
(If this is in a testcase, it is not difficult to compare JSON properly. For example, parse the JSON and compare objects attribute by attribute.)
If you are lumbered with a (so-called) JSON API where the order of attributes has some meaning, my advice is:
Complain. Submit a bug report. This is not a proper JSON API.
Look for a JSON library that provides a way to work around the bad design. For example, some libraries allow you to provide a Map class to be used when constructing a JSONObject. The default is usually HashMap, but you could use LinkedHashMap instead.

How to escape or remove "\" from the gson generated string?

I am loading a value from the property file and then passing it to gson method for converting it to final json object. However, the value coming from the property file has double quotes for which the gson is adding "\" to the output. I have scanned down the whole web but unable to find a solution
The property file contains
0110= This is a test for the renewal and the "Renewal no:"
Here's my code
public String toJSONString(Object object) {
GsonBuilder gsonBuilder = new GsonBuilder();
Gson gson = gsonBuilder.create();
//Note object here is the value from the property file
return gson.toJson(object);
}
This produces
"{ResponseCode:0110,ResponseText:This is a test for the renewal and the \"Renewal no:\"}"
I am not sure in the output, why it is adding or wrapping the \ around the literals or where ever we have the double quotes in the property file value?
Based on comments on your question, the object parameter is actually referencing a Java String with the value
{ResponseCode:0110,ResponseText:This is a test for the renewal and the "Renewal no:"}
I can't say why, but that's what your String contains.
String is a special type which Gson interprets as a JSON string. Since " is a special character that must be escaped in JSON strings, that's what Gson does and produces the JSON string.
"{ResponseCode:0110,ResponseText:This is a test for the renewal and the \"Renewal no:\"}"
The \ character is escaping special characters like " in the string. You can't store a " in a string without a leading . It has to be \".
You remove the slashes when you display any output string.
Apache Commons has a library for handling escaping and unescaping strings: https://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/StringEscapeUtils.html

Java Json / Gson put json encoded string to jsonObject without string escapes

i first create a Json String with
String myJsonString = new Gson().toJson(myElement);
this works fine.
After that, i want to add this String to anothe big jsonObject to send it to backend with other vars.
jsonObject.put("Tests",myJsonString);
but with this line of code the special character will be escaped and the parser on the backend didnt get it.
How can I avoid it, that myJsonString will be serialized again?
jsonObject.put("Tests",myElement);
doesnt work, because after that there are only references in the jsonObject but no values.
jsonObject.put("Tests", new JSONObject(myJsonString));
(assuming jsonObject is of type org.json.JSONObject)

Char array replace characters

I'm creating json response in quite sophisticated framework and have problems with json escaping.
I'm able to grab char[] with text I'd like to escape. What's the proper (and the best in case of performance) way to do escaping. Keep in mind that it's not replacing character with character - it's replacing (mostly) one character with two characters, so the array has to be rearranged.
Using common (Apache, Google, ...) libraries would be appreciated.
edit:
Gson library looks fine for my purposes, however there's a problem with snippet:
Gson gson2 = new Gson();
String json = gson2.toJson(new String(buf));
cause it encodes html as well. My task is to do just json encoding for given HTML markup, so I don't want to have tags encoded like \u003e.
I alway use Gson from Google. It work fine for me and no escaping problems I meat ever. Try it.
Gson gson = new Gson();
// To json:
String result = gson.toJson(yourObject);
// From json:
YourObject object= gson.fromJson(result, YourObject.class);
You need
GsonBuilder builder = new GsonBuilder();
builder.disableHtmlEscaping();
String result = builder.create().toJson(yourObject);

How to decode a json string with gson in java?

I have a json string (the stream of social network Qaiku). How can I decode it in Java?
I've searched but any results work for me.
Thank you.
Standard way of object de-serialization is the following:
Gson gson = new Gson();
MyType obj = gson.fromJson(json, MyType.class);
For primitives corresponding class should be used instead of MyType.
You can find more details in Gson user's guide. If this way does not work for you - probably there's some error in JSON input.
As an example using Gson, you could do the following
Gson gson = new Gson();
gson.fromJson(value, type);
where value is your encoded value. The trick comes with the second parameter - the type. You need to know what your decoding and what Java type that JSON will end in.
The following example shows decoding a JSON string into a list of domain objects called Table:
http://javastorage.wordpress.com/2011/03/31/how-to-decode-json-with-google-gson-library/
In order to do that the type needs to be specified as:
Type type = new TypeToken<List<Table>>(){}.getType();
Gson is available here:
http://code.google.com/p/google-gson/

Categories

Resources