Currently I am developing a Java service which converts an class to json string, however when there is any one attribute with the character ” (It is word quotes) then the marshalling process returns CCH character (CANCEL CHARACTER) which appears of this way in notepad++ app.
The following code shows that objectClassX is the object for transforming:
import com.fasterxml.jackson.databind.ObjectMapper;
ObjectMapper mapper=mapper = new ObjectMapper();
byte[] bytesJson= mapper.writeValueAsBytes(objectClassX);
String stringJson = bytesJson!=null?new String(bytesJson , "UTF-8"):"VACIO";
I am using the byteJson for doing some things, but finnaly it is has been converted to String.
I want remplacing the CCH character by an blank space, but I would like doing from ObjectMapper configuration, and of this way I would avoid doing from replace code from String.
Thanks for your help.
Regards.
Related
Using PrettyPrintWriter to pretty print the xml file
In the generated xml file the ' (apostrophe) is getting written as &apos
Want it to print as '
Using the following
xstream.marshal(obj, new PrettyPrintWriter(writer)) to pretty print
,any suggestions on how to print the escape characters as it is?
You can provide your own implementation of PrettyPrintWriter, which extends that class and overrides its writeText(QuickWriter, String) method.
In its most basic form that would be something like this:
import com.thoughtworks.xstream.core.util.QuickWriter;
import com.thoughtworks.xstream.io.xml.PrettyPrintWriter;
import java.io.Writer;
public class MyPrettyPrintWriter extends PrettyPrintWriter {
public MyPrettyPrintWriter(Writer writer) {
super(writer);
}
#Override
public void writeText(QuickWriter writer, String string) {
writer.write(string);
}
}
You would use this as follows:
String s = "Foo'Bar";
XStream xstream = new XStream();
FileWriter writer = new FileWriter("my_demo.xml");
xstream.marshal(s, new MyPrettyPrintWriter(writer));
The output file contains the following:
<string>Foo'Bar</string>
This is basic - it just passes the tag contents through to the file unchanged - nothing is escaped.
You are OK for content containing ", ' and >. But this will be a problem for text containing > and & - which should still be escaped. So you can enhance your writeText method to handle those cases as needed. See What characters do I need to escape in XML documents? for more details.
Note also this is only for text values - not for XML attributes. There is a separate writeAttributeValue method for that (probably not needed in your scenario).
It is worth adding: There should be no need to do any of this. The XML is valid, with escaped values such as '. Any process (any half-way decent XML library or tool) reading that data should handle them correctly.
I want to convert a UTF-8 string to escape \uXXX format in value of JSON Object.
I used both JSON Object and Gson, but did not work for me in this case:
JSONObject js = new JSONObject();
js.put("lastReason","nguyễn");
System.out.println(js.toString());
and
Gson gson = new Gson();
String new_js = gson.toJson(js.toString());
System.out.println(new_js);
Output: {"test":"nguyễn"}
But i am expect that my result is:
Expected Output: {"test":"nguy\u1EC5n"}
Any solutions for this case, please help me to resolve it.
You can use apache commons-text library to change a string to use Unicode escape sequences. Use org.apache.commons.text.StringEscapeUtils to translate the text before adding it to JSONObject.
StringEscapeUtils.escapeJava("nguyễn")
will produce
nguy\u1EC5n
One possible problem with using StringEscapeUtils might be that it will escape control characters as well. If there is a tab character at the end of the string it will be translated to \t. I.e.:
StringEscapeUtils.escapeJava("nguyễn\t")
will produce an incorrect string:
nguy\u1EC5n\t
You can use org.apache.commons.text.translate.UnicodeEscaper to get around this but it will translate every character in the string to a Unicode escape sequence. I.e.:
UnicodeEscaper ue = new UnicodeEscaper();
ue.translate(rawString);
will produce
\u006E\u0067\u0075\u0079\u1EC5\u006E
or
\u006E\u0067\u0075\u0079\u1EC5\u006E\u0009
Whether it is a problem or not is up to you to decide.
I am having user defined object Customer which has multiple attributes ,in one of the attributes we can have single , double quotes and backslash as well. While converting the object to string Gson library is adding backslash in it.
I am using below code to achive this but it is not working.
Gson gson = new GsonBuilder().disableHtmlEscaping().create();
JsonElement jsonString = gson.toJsonTree(triggerModel);
Output is
{
"customerId": "1234",
"customerName": "Loren",
"customerAddress": [
{
"postalcode": "67676",
"lane": "\"LA16767",
"houseNumber": "2025",
"society": "null"
}
]
}
In lane attribute the original value was "LA16767 but it is adding one backslash character. How to write this in such a way string with single ,double quotes and backslash are handled using same line of code.
Output provided by Gson is correct because "lane": ""LA16767" would not have been a valid json.
From json docs
A string is a sequence of zero or more Unicode characters, wrapped in double quotes, using backslash escapes. A character is represented as a single character string. A string is very much like a C or Java string.
You had mentioned :
How to write this in such a way string with single ,double quotes and backslash are handled using same line of code.
You need not do anything special to handle single ,double quotes and backslash characters. Gson will automatically escape them for you.
Any app (server, UI, etc,) who is consuming your json, will correctly parse "\"LA16767" as "LA16767 going by the json conventions.
I have a json string with SUBSTITUTE () utf-8 character. I'm getting parsing exception when I try to convert json string to java object using jackson. Can you please let me know how to encode and decode utf-8 characters ?
ObjectMapper mapper = new ObjectMapper();
mapper.readValue(jsonString, MY_DOMAIN_OBJECT.class);
jsonString:
{"studentId":"753253-2274", "information":[{"key":"1","value":"Get alerts on your phone(SUBSTITUTE character is present here. Unable to paste it)To subscribe"}]}
Error:
Illegal unquoted character ((CTRL-CHAR, code 26)): has to be escaped using backslash to be included in string value
Can you try this?
ObjectMapper mapper = new ObjectMapper();
mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true);
mapper.readValue(jsonString, MY_DOMAIN_OBJECT.class);
I hope it helps you:
Javadoc
Feature that determines whether parser will allow JSON Strings to contain unquoted control characters (ASCII characters with value less than 32, including tab and line feed characters) or not. If feature is set false, an exception is thrown if such a character is encountered.
Since JSON specification requires quoting for all control characters, this is a non-standard feature, and as such disabled by default.
So i have this String e.g.
"B\z#b#s#rB{FpMgBrD~DK|"
But Spring is producing this at json:
"B\\z#b#s#rB{FpMgBrD~DK|"
And it's the same with any string that has a backslash \. Replacing the character before generating the json is useless, since the String is correct before the json is generated.
Every client that consumes the service could .replace("\\","\\\\") the json, but I wonder if there will be a cleaner way to solve the problema and at server side.
Here is the code for the WS:
#RequestMapping(value = "/rest/sinc/{ms}", method = RequestMethod.GET, produces="application/json;charset=UTF-8")
#ResponseBody
public String sincronizar(#PathVariable("ms") Long ms) {
return sincService.getSinc(ms).toString();
}
I have tried other ways to generate the json with libraries like Gson but the result is the same.
That is the expected behavior in JSON. \ needs to be escaped. See the specification, here.
All Unicode characters may be placed within the quotation marks,
except for the characters that must be escaped: quotation mark,
reverse solidus, and the control characters (U+0000 through U+001F).