在Java中转义JSON字符串 [英] Escape JSON string in Java

查看:3727
本文介绍了在Java中转义JSON字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Google的 com.google.api.client.json.GenericJson com.fasterxml.jackson.core.JsonGenerator 。我想序列化JSON对象并转义引号和反斜杠,以便我可以在Bash中传递该字符串。然后反序列化该字符串。

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 生成简单的JSON,但 \ n 等未被转义:

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}"

我不想重新发明轮子,所以我想用杰克逊或者现有的API,如果可能的话。

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

推荐答案

不需要其他依赖项:您正在寻找 JsonStringEncoder #quoteAsString(String)

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

点击 JsonStringEncoder javadoc

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}"

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

这篇关于在Java中转义JSON字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆