java 杰克逊有没有像 JSON.stringify 这样的东西?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28683020/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is there anything like JSON.stringify in Hymanson?
提问by Bob Kuhar
I find myself needing to JSON.stringify(objectMapper.writeValueAsString(someJavaBean));
server side in Java as I make an HttpClient call to another service in our infrastructure. Does Hymanson have any such function? Is there an easy way to do this without adding another dependency to my project?
我发现自己需要JSON.stringify(objectMapper.writeValueAsString(someJavaBean));
在 Java 中使用服务器端,因为我对基础设施中的另一个服务进行了 HttpClient 调用。Hyman逊有这样的功能吗?有没有一种简单的方法可以在不向我的项目添加另一个依赖项的情况下做到这一点?
If it matters, we are Hymanson 2.3.2.
如果重要的话,我们是 Hymanson 2.3.2。
What I need to do is convert some JSON like
我需要做的是转换一些 JSON 之类的
{ "first_name" : "Robert", "last_name" : "Kuhar" }
Into a Javascript String like
变成一个 Javascript 字符串,比如
"{ \"first_name\" : \"Robert\", \"last_name\" : \"Kuhar\" }"
Its not as simple as Replace all the quotes with \", is it? Like what happens if there are quotes embedded in the values? Or some of the values are single quote delimited? It seems like there should be a library call to do this.
它不像用 \" 替换所有引号那么简单,是吗?就像如果在值中嵌入引号会发生什么?或者一些值是单引号分隔的?似乎应该有一个库调用来做到这一点.
Any advice?
有什么建议吗?
回答by JB Nizet
String json = objectMapper.writeValueAsString(someObject);
String encodedASecondTime = objectMapper.writeValueAsString(json);
As simple as that. Not sure why you would want that, though, since a JSON value is a valid object literal already. You can do
就如此容易。不过,不确定您为什么要这样做,因为 JSON 值已经是一个有效的对象字面量。你可以做
String json = objectMapper.writeValueAsString(someObject);
and then generate javascript like
然后生成 javascript 之类的
"var obj = " + json + ";"