Gson, how should I treat a backslashes while deserializing json to objects? - java

I'm using Google Gson 2.3.1 library.
When I receive the following json string:
{"PC" : "Domain\Host"}
I receive in POJO DomainHost string without backslash. What is the correct way to deal with it?
Ask from serializer man to add an escape backslash like that Domain\\Host?
Check for backslashes on my side and insert escaping backslash prior to deserializing?
Maybe GSON library know to deal with it?
Didn't find anything not in manual neither in google that can help me.
Currently I tend to choose 2nd option, but not sure that it's a good idea.
Thank you.

Related

Cleanest way to deserialize a non-standard (wrong) format of list of JSON string that doesn't have quote

I'm trying to deserialize a Java String to a List of String. Due to some reason, the input may come in two formats:
"[\"string1\", \"string2\"]"
or
"[string1, string2]"
The library I'm using is Jackson databind.
For the first case, it's a typical, easy case that Jackson supports.
For the second, I understand it's not a correct format of JSON and I can hack to achieve the goal by splitting this String by , and remove []s etc, but just would like to know if someone knows a clean way to deserialize something like that.
Thanks in advance.
To answer your question, you can look into YAML parsers. :)
Jackson has an extention for YAML support so that would be your clean solution.
YAML is a superset of JSON so it can parse any valid JSON... as well as many more complex transcripts (like strings without ").

split JSON and string in android

My HTTP Request responds with combination of string and JSON, something like this:
null{"username:name","email:email"}
I need only the JSON part.
I directly tried parsing as json object, which was not right of course. I tried splitting it: serverResponse.split("{"), but android does not allow to parse with this character because it is not a pattern. Any suggestion how i can achieve this?
String.split uses regular expressions, and since '{' is a special character in regular expressions, you should escape it like this: serverResponse.split("\\{").
It would be better to change the server side, but you can also just use split. The only thing you need to do is escape your {.
String json = serverResponse.split("\\{")[1];
It is a bad idea and a bad practice to split a Json. If one day it you change on the serve side, it may pick a wrong part of your Json Object.
I recommend you to PARSE it, even if it is simple and small.

Jackson cannot parse control character

In my API response, I have control-p character. Jackson parser fails to serialize the character and throws an error
com.fasterxml.jackson.core.JsonParseException: Illegal unquoted
character ((CTRL-CHAR, code 16)): has to be escaped using backslash to
be included in string value
I have investigated and found that Jackson library actually tries to catch for ctrl-char.
Can anyone suggest solutions or work around for this? Thanks in advance.
I was able to fix similar problem by setting Feature.ALLOW_UNQUOTED_CONTROL_CHARS (documentation) on JsonParser
.
The code in my case looks:
parser.setFeatureMask(parser.getFeatureMask() | JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS.getMask());
As stated by others, such JSON is invalid, but in case you have no chance to change JSON, this should help.
Have you tried to configure the mapper to force escape non-ASCII?
This might be enough:
mapper.configure(JsonGenerator.Feature.ESCAPE_NON_ASCII, true);
see documentation
But I agree with StaxMan: the JSON response should be well formatted.
Content you get is not valid JSON -- as per JSON specification, control characters MUST be escaped within String values, and CAN NOT exist outside of them. So I would recommened getting input data fixed; it is corrupt, and whoever is sending it is not doing good job of cleansing it, or properly escaping.
Barring that, you can write a Reader (or even InputStream) that filters out or converts said control characters.

How to add a URL String in a JSON object

I need to add a URL typically in the format http:\somewebsite.com\somepage.asp.
When I create a string with the above URL and add it to JSON object json
using
json.put("url",urlstring);
it's appending an extra "\" and when I check the output it's like http:\\\\somewebsite.com\\somepage.asp
When I give the URL as http://somewebsite.com/somepage.asp
the json output is http:\/\/somewebsite.com\/somepage.asp
Can you help me to retrieve the URL as it is, please?
Thanks
Your JSON library automatically escapes characters like slashes. On the receiving end, you'll have to remove those backslashes by using a function like replace().
Here's an example:
string receivedUrlString = "http:\/\/somewebsite.com\/somepage.asp";<br />
string cleanedUrlString = receivedUrlString.replace('\', '');
cleanedUrlString should be "http://somewebsite.com/somepage.asp".
Hope this helps.
Reference: http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#replace(char,%20char)
Tichodroma's answer has nailed it. You can solve the "problem" by storing valid URLs.
In addition, the JSON format requires that backslashes in strings are escaped with a second backslash. If the 2nd backslash is left out, the result is invalid JSON. Refer to the JSON syntax diagrams at http://www.json.org
The fact that the double backslashes are giving you problems actually means that the software that is reading the files is broken. A properly written JSON parser will automatically de-escape the strings. The site I linked to above lists many JSON parser libraries written in many languages. You should use one of these rather than trying to write the JSON parsing code yourself.

Making JSON not Escape Forward Slashes

This is an extenuation of this question:
JSON: why are forward slashes escaped?
So I understand why JSON escapes the forwards slashes when I create a JSONArray that has Strings that contain URLs (links) in each of its indices. I would like to now know how to make JSON not escape these forward slashes when I serialize a String like so:
[['documentary', 'http://www.google.com/#q=documentary']]
into a JSONArray. I was thinking of iterating through the Strings and removing any instance where there is a backslash, but I was wondering if there was a more efficient way of doing this or a way to have it so that the above string would not automatically be escaped as follows:
[['documentary', 'http:\/\/www.google.com\/#q=documentary']]
Thank you! Let me know if anything is unclear.
Is it json-simple that you are using? They have an open issue for this, no luck with a fix so far:
https://github.com/fangyidong/json-simple/issues/8
I just hacked their source code.

Categories