Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Escape JSON string in Java

Tags:

java

json

jackson

I'm using Google's com.google.api.client.json.GenericJson and com.fasterxml.jackson.core.JsonGenerator. I would like to serialize JSON object and escape quotes and backslashes so that I can pass that string in Bash. And afterwards deserialize that string.

GenericJson.toString produces simple JSON, but \n etc. are not escaped:

{commands=ls -laF\ndu -h, id=0, timeout=0}

is there a simple way how to get something like this:

"{commands=\"ls -laF\\ndu -h\", id=0, timeout=0}"

I don't want to reinvent the wheel, so I'd like to use Jackson or an existing API, if possible.

like image 697
Tombart Avatar asked Feb 05 '14 11:02

Tombart


People also ask

How do you escape a string?

In the platform, the backslash character ( \ ) is used to escape values within strings. The character following the escaping character is treated as a string literal.


1 Answers

No additional dependencies needed: You're looking for JsonStringEncoder#quoteAsString(String).

Click for JsonStringEncoder javadoc

Example:

import com.fasterxml.jackson.core.io.JsonStringEncoder;

JsonStringEncoder e = JsonStringEncoder.getInstance();
String commands = "ls -laF\\ndu -h";
String encCommands = new String(e.quoteAsString(commands));
String o = "{commands: \"" + encCommands + "\", id: 0, timeout: 0}"

Ref: http://fasterxml.github.io/jackson-core/javadoc/2.1.0/com/fasterxml/jackson/core/io/JsonStringEncoder.html

like image 117
Barett Avatar answered Sep 18 '22 01:09

Barett