I'm trying to put a json in a javascript file in java, but when I write the json to a string, the string doesn't appear to be a valid json for javascript; it is missing some escapes. (This is happening in a string in the json which I formatted as a faux json.)
For example, this would be a valid json in my javascript file:
{
"message":
"the following books failed: [{\"book\": \"The Horse and his Boy\",\"author\": \"C.S. Lewis\"}, {\"book\": \"The Left Hand of Darkness\",\"author\": \"Ursula K. le Guin\"}, ]"
}
Here's what I get, though, where the double quotes aren't escaped:
{
"message":
"The following books failed: [{"book": "The Horse and his Boy","author": "C.S. Lewis"}, {"book": "The Left Hand of Darkness","author": "Ursula K. le Guin"}, ]"
}
I get the second result when I do this:
new ObjectMapper().writer().writeValueAsString(booksMessage);
But when I write it directly to a file with jackson, I get the first, good result:
new ObjectMapper().writer().writeValue(fileToWriteTo, booksMessage);
So why does jackson escape differently when writing to a file, and how do I get it to escape like that for me when writing to a string?
The writeValue() methods of the ObjectWriter class encode the input text.
You don't need to write to a file. An alternative approach for getting the same string could be:
StringWriter sw = new StringWriter();
new ObjectMapper().writer().writeValue(sw, booksMessage);
String result = sw.toString();
I added
booksJson = Pattern.compile("\\\\").matcher(booksJson).replaceAll("\\\\\\\\");
which escapes all the escape characters. That way when I write it to file and it removes the escapes, I still have the escapes I need. So turns out my real question was how to write to file without Java escapes being removed.
I'm very late to the party but I faced a similar problem and I realized it was not a problem with Jackson or my data. It was Java. I was reading from a JSON file and then trying to write it into a template HTML file.
I had a line my original JSON like yours, something like:
{"field" : "This field contains what looks like another JSON field: {\"abc\": \"value\"}"}
And when I wrote the above to a string, the backslash before the quotes in abc and value disappeared. I noticed that the contextual help for String.replaceAll mentioned something about Matcher.quoteReplacement. I went from this:
template = template.replaceAll("%template%", jsonDataString);
to this:
Pattern pattern = Pattern.compile("%template%");
Matcher matcher = Pattern.matcher(template);
matcher.replaceAll(matcher.quoteReplacement(jsonDataString));
Problem solved.
Matcher.quoteReplacement
Related
In Java, I want to serialize a JSON string containing values such as 12/28 to 12\/28
Using Apache lib StringEscapeUtils and then for serialization, using jackson lib, output comes out as 12\\/28:
Current output:
{
"expiryDate": "12\\/28"
}
However, I want the output to be "12/28"
Desired output:
{
"expiryDate": "12\/28"
}
Any suggestions?
According to the JSON specification (e.g. the syntax graphs at http://json.org), \/ is a valid JSON escape sequence.
However the sequence \/ means the the same thing as /, so there is little point in using \/. (A conformant JSON parser will read it as a /.)
I am not was not aware of any JSON library that will output a / as \/ when serializing data to JSON. However, it appears that json-simple (link, link) always escapes a / as \/:
I don't know why they decided to do that.
The code that implements this behavior is in the method org.json.simple.JSONValue.
On the other hand, I am not aware of a JSON library that won't escape a literal \ in a string when it sees one. (That would be broken, IMO, unless it was part of a design feature for stitching together already formatted JSON string fragments.)
After exploring some options, was able to achieve desired output using below.
Library used:
compile 'com.googlecode.json-simple:json-simple:1.1.1'
Code Sample:
JSONObject jsonObject = new JSONObject();
jsonObject.put("expiryDate", "12/28");
String jsonString = jsonObject.toString();
Output:
{"expiryDate":"12\/28"}
I'm calling 3rd party API and receiving as a response json:
{\"name\":\"name \\"A\\" and other\",\"id\":1}
If I try to map it like that I'm getting sure that:
Unexpected character ('\' (code 92)): was expecting double-quote to start field name
How could I map it with jackson? Should I remove backslashes with regex? Like every \" -> " and \\" -> \"
That is not well formed. What are you planning to do looks fine
File a bug against whoever is producing this broken output; it is not valid JSON.
{\"name\":\"name A and other\",\"id\":1}, this is the valid form of JSON or
{"name":"name A and other","id":1} it is also valid.
If this is not possible to do it, ask your vendor to validate the JSON structure
I need to write an attribute on a JSON document, and this attribute is an URL
This is my code:
String url = "http://localhost:1028/accumulate";
JSONObject cabecera = new JSONObject();
cabecera.put("reference", url);
But when I create the JSON,this attibute is writted in this way:
"reference":"http:\/\/localhost:1028\/accumulate",
So, the service that receives the JSON String, it's sending me an error:
<subscribeContextResponse>
<subscribeError>
<errorCode>
<code>400</code>
<reasonPhrase>Bad Request</reasonPhrase>
<details>JSON Parse Error: <unspecified file>(1): invalid escape sequence</details>
</errorCode>
</subscribeError>
</subscribeContextResponse>
What is the correct way to write the URL??
Thanks in advance
But when I create the JSON,this attibute is writted in this way:
"reference":"http:\/\/localhost:1028\/accumulate",
That's fine, the backslashes are harmless, whatever you're using to serialize to JSON is just being a bit hyper with its escapes. The string represented by the above contains no backslashes at all, just slashes. \/ inside a JSON string is exactly the same as /, as we can see from the highlighted rule from http://json.org:
("solidus" is a fancy term for slash)
When I am sending a TextEdit data as a JSON with data as a combination of "; the app fails every time.
In detail if I am entering my username as anything but password as "; the resultant JSON file looks like:-
{"UserName":"qa#1.com","Password":"\";"}
I have searched a lot, what I could understand is the resultant JSON data voilates the syntax which results in throwing Default exception. I tried to get rid of special symbol by using URLEncoder.encode() method. But now the problem is in decoding.
Any help at any step will be very grateful.
Logcat:
I/SW_HttpClient(448): sending post: {"UserName":"qa#1.com","Password":"\";"}
I/SW_HttpClient(448): HTTPResponse received in [2326ms]
I/SW_HttpClient(448): stream returned: <!DOCTYPE html PUBLIC ---- AN HTML PAGE.... A DEFAULT HANDLER>
Hi try the following code
String EMPLOYEE_SERVICE_URI = Utils.authenticate+"?UserName="+uid+"&Email="+eid+"&Password="+URLEncoder.encode(pwd,"UTF-8");
The JSON you provided in the Question is valid.
The JSON spec requires double quotes in strings to be escaped with a backslash. Read the syntax graphs here - http://www.json.org/.
If something is throwing an exception while parsing that JSON, then either the parser is buggy or the exception means something else.
I have searched a lot, what I could understand is the resultant JSON data voilates the syntax
Your understanding is incorrect.
I tried to get rid of special symbol by using URLEncoder.encode() method.
That is a mistake, and is only going to make matters worse:
The backslash SHOULD be there.
The server or whatever that processes the JSON will NOT be expecting random escaping from a completely different standard.
But now the problem is in decoding.
Exactly.
Following provided JSON can be parsed through GSON library with below code
private String sampledata = "{\"UserName\":\"qa#1.com\",\"Password\":\"\\\";\"}";
Gson g = new Gson();
g.fromJson(sampledata, sample.class);
public class sample {
public String UserName;
public String Password;
}
For decoding the text I got the solution with..
URLDecoder.decode(String, String);
I have a big json string which i will be getting as a request from the UI , which will be converted to a String and parsed .
I want to simulate the similar environment for testing locally , so for this purpose i captured the JSon format.
Currently i am manually adding "/" to this big json string .
Is there any other way to achieve this ??
For example i got this json
{"age":29,"messages":["msg 1","msg 2","msg 3"],"name":"Preethi"}
and converted that into
String str = "{\"age\":\"29\",\"messages\":[\"msg 1\",\"msg 2\",\"msg 3\"],\"name\":\"mkyong\"}";
Is there any other way to achieve this ??
On the client-side, do a search and regex "replace all" of double-quotes into single quotes on the desired form field before actually sending the request.
Actually, Java doesn't have verbatim string literals.
If you want a Java-like (and Java-VM-based) language that does, however, you might want to look at Groovy which has various forms of string literal.
we have in build method to convert jsonObject to string. Why don't you use that.
JSONObject json = new JSONObject();
json.toString();