I want to generate JSON string from given string but with single backslash character before single quote character like this \'. For example I have string "you are the 'great'" and want output like this "you are the \'great\'". I am using jackson object mapper class and following is the code:
String str = "you are the 'great'";
String jsonStr = "";
System.out.println(str);//Line-1
ObjectMapper mapper = new ObjectMapper();
try
{
jsonStr = mapper.writeValueAsString(str);
}
catch (IOException e)
{
e.printStackTrace();
}
System.out.println(jsonStr);//Line-2
So based on that I have performed following testcases:
Input string: "you are the \'great\'"
Output of Line-1: you are the 'great'
Output of Line-2: you are the 'great'
Input string: "you are the \\'great\\'"
Output of Line-1: you are the \'great\'
Output of Line-2: you are the \\'great\\'
But I am not able to get the expected output. Please provide some solution.
Note: Here to explain you the problem I have taken string as a input but actually I have some string properties in object and want Json string of that object.
Related
I am using objectMapper to convert object as string. While converting mappper is creating invalid string. How can I keep JsonNode/JsonObject string intact while using object mapper.
JsonObject:
{
"provision": " purpose of usefuleness.\n\n shall not use personal-provided facilities.\n\nWe shall not be required to pay you.
}
Is Converted to
{
"provision": " purpose of usefuleness.
\shall not use personal-provided facilities.
\We shall not be required to pay you.
}
Used:
new ObjectMapper().writeValuesAsString(json);
How can keep the original String intact.
with
new JsonObject(String)
or
when using
new ObjectMapper().writeValuesAsString(json);
Just unquote special character \n
String body = "{\"provision\" : \"purpose of usefuleness.\\n\\n shall not use personal-provided facilities.\\n\\nWe shall not be required to pay you.\"}";
ObjectMapper mapper = new ObjectMapper();
String result = null;
try {
JsonNode node = mapper.readTree(body);
result = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(node);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(result);
{
"provision" : "purpose of usefuleness.\n\n shall not use personal-provided facilities.\n\nWe shall not be required to pay you."
}
this is my .json file:
{"Usuarios":[{"password":"admin","apellido":"Admin","correo":"Adminadmin.com","direccion":"Admin","telefono":"Admin","nombre":"Admin","username":"admin"}]}
(I tried to translate my code from Spanish to English in the comments as best I could <3)
The function that writes in the JSON is this one:
public void agregarUsuario(String nombre, String apellido, String direccion, String telefono, String correo, String username, String password) {
try {
//String jsonString = JsonObject.toString();
JSONObject usuarios = getJSONObjectFromFile("/usuarios.json");
JSONArray listaUsuario = usuarios.getJSONArray("Usuarios");
JSONObject newObject = new JSONObject();
newObject.put("nombre", nombre);
newObject.put("apellido", apellido);
newObject.put("direccion", direccion);
newObject.put("telefono", telefono);
newObject.put("correo", correo);
newObject.put("username",username);
newObject.put("password", password);
listaUsuario.put(newObject);
usuarios.put("Usuarios",listaUsuario);
ObjectOutputStream outputStream = null;
outputStream = new ObjectOutputStream(new FileOutputStream("C:\\Users\\Victor\\eclipse-workspace\\Iplane\\assets\\usuarios.json"));
outputStream.writeUTF(usuarios.toString());
outputStream.flush();
outputStream.close();
}catch(JSONException e) {
e.printStackTrace();
}catch(Exception e) {
System.err.println("Error writting json: " + e);
}
So, if in my "create user" JFrame window ,I create a new user with "asdf" as info within all the user's details, I should get the following JSON file:
{"Usuarios":[{"password":"admin","apellido":"Admin","correo":"Adminadmin.com","direccion":"Admin","telefono":"Admin","nombre":"Admin","username":"admin"},{"password":"asdf","apellido":"asdf","correo":"asdf","direccion":"asdf","telefono":"asdf","nombre":"asdf","username":"asdf"}]}
And yes! that happens! but I got also, some weird ascii/Unicode symbols in front if my JSON main object. I cant copy the output here, so this is my output on imgur: link.
Why this problem happens? how could I fix it?
If someone need my json file reader (maybe the problem is there) here you go:
public static InputStream inputStreamFromFile(String path) {
try {
InputStream inputStream = FileHandle.class.getResourceAsStream(path); //charge json in "InputStream"
return inputStream;
}catch(Exception e) {
e.printStackTrace(); //tracer for json exceptions
}
return null;
}
public static String getJsonStringFromFile(String path) {
Scanner scanner;
InputStream in = inputStreamFromFile(path); //obtains the content of the .JSON and saves it in: "in" variable
scanner = new Scanner(in); //new scanner with inputStream "in" info
String json= scanner.useDelimiter("\\Z").next(); //reads .JSON and saves it in string "json"
scanner.close(); //close the scanner
return json; //return json String
}
public static boolean objectExists (JSONObject jsonObject, String key) { //verifies whether an object exist in the json
Object o;
try {
o=jsonObject.get(key);
}catch(Exception e) {
return false;
}
return o!=null;
}
public static JSONObject getJSONObjectFromFile(String path) { //creates a jsonObject from a path
return new JSONObject(getJsonStringFromFile(path));
}
So, after writing in JSON file, I cant do anything with it, because with this weird symbols, I got errors in my json: "extraneus input: (here are the symbols) expecting [STRING, NUMBER, TRUE, FALSE, {..."
writeUTF does not write standard unicode but prepends the output with two bytes of length information
If you use writeUTF intentionally, you have to use readUTF to read the data again. Otherwise I would suggest using an OutputStreamWriter.
writeUTF()
Writes two bytes of length information to the output stream, followed
by the modified UTF-8 representation of every character in the string
s. If s is null, a NullPointerException is thrown. Each character in
the string s is converted to a group of one, two, or three bytes,
depending on the value of the character.
** Edit to clarify OutputStreamWriter:
To use the OutputStreamWriter just replace the ObjectOutputStream with OutputStreamWriter and use write instead of writeUTF.
You might find this small tutorial helpfull: Java IO: OutputStreamWriter on jenkov.com
This is my method
public String buildJsonData(String username , String message)
{
JsonObject jsonObject = Json.createObjectBuilder().add("Username",username+":"+message).build();
StringWriter stringWriter = new StringWriter();
try(JsonWriter jsonWriter = Json.createWriter(stringWriter))
{
jsonWriter.write(jsonObject);
}
catch(Exception e)
{
System.out.print("buildJsonData ="+e);
}
return stringWriter.toString();
}
If i input username as john and message as hello.I get output as
{"Username":"john:hello"}
But I want output without braces and doublequotes I want my output as
John:hello
I tried to split it using array[0] but didn't get the output.Is it possible in json to get my desired output(without braces and quotes).
On the sending end, you would put the Username and Message entities into a JSONObject and send the resulting string over the network.
On the receiving end, you would unmarshal the JSON to extract the entities. You can then format them however you like.
Please read about JSON encoding here.
This is a simple example:
private String getResponse(){
JSONObject json = new JSONObject();
try {
json.put("Username", "John");
json.put("Message", "Hellow");
} catch (JSONException e) {
e.printStackTrace();
}
return json.toString();
}
private void receiver(){
try {
JSONObject response = new JSONObject(getResponse());
String username = response.getString("Username");
String message = response.getString("Message");
System.out.println(String.format("%s : %s", username,message));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Your structure is not really JSON.
A json structure would be like
{
Username : "John",
Message : "Hello"
}
Anf if your want to really use JSON, there is not way to remove braces and quotes. This IS Json.
If you want to output only the part you quoted, store the json value in a variable
String myoutput = stringWriter.toString();
And then remove the parts you don't want with replace() or a regexp
Braces are part of the JSON notation - they indicate an object. If you remove them, then it's not JSON any more. Same goes for double quotes.You are creating your JSON object as:
Json.createObjectBuilder().add("Username",username+":"+message)
This creates an object with property named Username and value john:hello. Again, this is the JSON notation. It's not intended to be read directly, but to facilitate data transfer between applications (on the same or different devices).
If all you want to create is john:message, then instead of creating a JSON object, you should simply do:
String result = username + ":" + message;
return result;
I'm making requests to a HTTP server sending JSON string. I used Gson for serializing and deserializing JSON objects. Today I observed this pretty weird behavior that I don't understand.
I have:
String jsonAsString = gson.toJson(jsonAsObject).replace("\"", "\\\"");
System.out.println(jsonAsString);
That outputs exactly this:
{\"content\":\"Literal\",\"pos\":{\"left\":20,\"top\":20}}
Now I'm using OutputStreamWriter obtained from HttpURLConnection to make HTTP, PUT request with JSON payload. The foregoing request works fine:
os.write("{\"content\":\"Literal\",\"pos\":{\"left\":20,\"top\":20}}");
However, when I say:
os.write(jsonAsString);
...the request doesn't work (this server doesn't return any errors but I can see that when writing JSON as string object it doesn't do what it should). Is there a difference when using string literal over string object. Am I doing something wrong?
Here is the snippet:
public static void EditWidget(SurfaceWidget sw, String widgetId) {
Gson gson = new Gson();
String jsonWidget = gson.toJson(sw).replace("\"", "\\\"");
System.out.println(jsonWidget);
try {
HttpURLConnection hurl = getConnectionObject("PUT", "http://fltspc.itu.dk/widget/5162b1a0f835c1585e00009e/");
hurl.connect();
OutputStreamWriter os = new OutputStreamWriter(hurl.getOutputStream());
//os.write("{\"content\":\"Literal\",\"pos\":{\"left\":20,\"top\":20}}");
os.write(jsonWidget);
os.flush();
os.close();
System.out.println(hurl.getResponseCode());
} catch (IOException e) {
e.printStackTrace();
}
}
Remove the .replace("\"", "\\\"") instruction. It's unnecessary.
You're forced to add slashes before double quotes when you send a JSON String literal because in a Java String literal, double quotes must be escaped (otherwise, they would mark the end of the String instead of being a double quote inside the String).
But the actual String, in the bytecode, doesn't contain these backslashes. They're only used in the source code.
I am calling an API which returns a JSON response. While reading the JSON response there are some places where data has some special characters. I want to exclude these special characters while reading the response in an object. The JSON response looks like this:
{"data":[{"title":"PSY - GANGNAM STYLE (\uac15\ub0a8\uc2a4\ud0c0\uc77c) M\/V","content":All rights reserved."}]}
The Java code is this:
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "ISO-8859-1"), 8);
When I read the title key from the response, it gives me these special characters as well which I don't want. How do get rid of those? Do i need to specify some other encoding?
Data Source :http://pipes.yahoo.com/pipes/pipe.run?_id=920adeb2e95c15877e29dc678aa78dd7&_render=json&n=1
This isn't an encoding issue (like UTF-8), it's a JavaScript syntax issue. The "\uac15", for example, is JavaScript syntax that represents the Unicode character U+AC15, which is "강". Together, those escaped characters are the name of the song written in Hangul (Korean): "강남스타일".
It's normal and OK for your Java string to contain the backslash escape sequences. When you run that string though a JSON reader, you should get a JSON object containing the actual Hangul characters.
In response to your comment about getting wrong output from a JSON reader, that depends on what JSON library you're using (and how you're using it), which you didn't specify in the question. Here's an example that works for me using Jackson 2.1.0:
public final class JsonTest {
public static void main(final String[] args) {
final String json = "\"PSY - GANGNAM STYLE (\\uac15\\ub0a8\\uc2a4\\ud0c0\\uc77c) M\\/V\"";
System.out.println("JSON: " + json);
try {
// ObjectMapper is from Jackson 2.1 databind library.
final ObjectMapper mapper = new ObjectMapper();
final String decoded = mapper.readValue(json, String.class);
System.out.println("Decoded: " + decoded);
}
catch (final IOException e) {
e.printStackTrace();
}
}
}