Java Jackson 在 json 中添加反斜杠
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41815818/
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
Hymanson adds backslash in json
提问by Fran?ois Esthète
I'm building REST service on Jersey
and using Hymanson
to produce JSON from java classes of my model. Model with absolutely simple values, I think this is the most typical case. But I get strange result:
我正在构建 REST 服务Jersey
并使用Hymanson
它从我的模型的 Java 类生成 JSON。具有绝对简单值的模型,我认为这是最典型的情况。但我得到了奇怪的结果:
[{\"name\":\"Nick\",\"role\":\"admin\",\"age\":\"32\",\"rating\":47}]
My expecting result:
我期待的结果:
[{"name":"Nick","role":"admin","age":"32","rating":47}]
My source values of fields does NOT contains any special characters. These are simple words.
我的字段源值不包含任何特殊字符。这些都是简单的词。
There're my Java classes. Entity:
有我的 Java 课程。实体:
public class User {
private String name;
private String role;
private String age;
private Integer rating;
Class of rest service:
休息服务等级:
@ServiceConfig(contextName = "myContext")
@Path("/myrest")
public class MyRestService {
private static final String JSON_CONTENT_TYPE = MediaType.APPLICATION_JSON + ";charset=UTF-8";
@Context
protected HttpServletResponse response;
@GET
@Path("/users")
@OpenTransaction
@Produces({MediaType.APPLICATION_JSON})
public String findUsers(@QueryParam("department") String department) {
response.setContentType(JSON_CONTENT_TYPE);
PDTResponse.status(response).sendStatus(Response.Status.OK.getStatusCode());
List<User> users = new ArrayList<>();
users.add(new User("Nick", "admin", "32", 47));
String jsonInString;
ObjectMapper mapper = new ObjectMapper();
try {
jsonInString = mapper.writeValueAsString(users);
} catch (JsonProcessingException ex) {
jsonInString = "thrown exception: " + ex.getMessage();
}
return jsonInString;
}
I've tried to use annotation @JsonRawValue
for string properties:
我尝试@JsonRawValue
对字符串属性使用注释:
@JsonRawValue
private String name;
But result in this case was:
但在这种情况下的结果是:
[{\"name\":Nick,\"role\":admin,\"age\":32,\"rating\":47}]
And I expect:
我期望:
[{"name":"Nick","role":"admin","age":"32","rating":47}]
It's obvious that Hymanson somehow escapes the quotes in result json of response. But why does it do it, and most importantly how to avoid that? By themselves they are just strings! Without any quotes or special characters.
很明显,Hyman逊以某种方式转义了响应结果 json 中的引号。但是为什么要这样做,最重要的是如何避免这种情况?就其本身而言,它们只是字符串!没有任何引号或特殊字符。
I use Java 7
and Hymanson 2.6.1
. And Postman
to test result.
Any ideas for fix of my problem?
我使用Java 7
和Hymanson 2.6.1
。并Postman
测试结果。解决我的问题的任何想法?
回答by teacurran
All strings in java have to escape quotes in them. So jsonInString should have slashes in it. When you output jsonInString though it shouldn't have the quotes. Are you looking at it in a debugger or something?
Java 中的所有字符串都必须对其中的引号进行转义。所以 jsonInString 应该有斜线。当你输出 jsonInString 时,虽然它不应该有引号。你是在调试器还是其他东西中查看它?
回答by JuanGG
You can configure the ObjectMapper:
您可以配置 ObjectMapper:
final ObjectMapper mapper = new ObjectMapper();
mapper.configure(JsonGenerator.Feature.QUOTE_FIELD_NAMES, false);
mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
String jsonUsers = mapper.writeValueAsString(users);
more info here
更多信息在这里
回答by cassiomolin
Looks like you are over complicating your JAX-RS resource class.
看起来您的 JAX-RS 资源类过于复杂。
To use Hymanson as a JSON provider for Jersey 2.x, you don't need to create an ObjectMapper
instance like that. There's a better way to achieve it. Keep reading for more details.
要将 Hymanson 用作 Jersey 2.x 的 JSON 提供程序,您不需要创建这样的ObjectMapper
实例。有更好的方法来实现它。继续阅读以了解更多详情。
Adding Hymanson module dependencies
添加 Hymanson 模块依赖项
To use Hymanson 2.x as your JSON provider you need to add jersey-media-json-Hymanson
module to your pom.xml
file:
要将 Hymanson 2.x 用作您的 JSON 提供程序,您需要将jersey-media-json-Hymanson
模块添加到您的pom.xml
文件中:
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-Hymanson</artifactId>
<version>2.25.1</version>
</dependency>
Registering the Hymanson module
注册 Hymanson 模块
Then register the HymansonFeature
in your Application
/ ResourceConfig
subclass:
然后HymansonFeature
在您的Application
/ResourceConfig
子类中注册:
@ApplicationPath("/api")
public class MyApplication extends Application {
@Override
public Set<Class<?>> getClasses() {
Set<Class<?>> classes = new HashSet<Class<?>>();
classes.add(HymansonFeature.class);
return classes;
}
}
@ApplicationPath("/api")
public class MyApplication extends ResourceConfig {
public MyApplication() {
register(HymansonFeature.class);
}
}
If you don't have an Application
/ ResourceConfig
subclass, you can register the HymansonFeature
in your web.xml
deployment descriptor. The specific resource, provider and feature fully-qualified class names can be provided in a comma-separated valueof jersey.config.server.provider.classnames
initialization parameter.
如果您没有Application
/ResourceConfig
子类,则可以HymansonFeature
在web.xml
部署描述符中注册。可以在初始化参数的逗号分隔值中提供特定资源、提供者和功能完全限定的类名jersey.config.server.provider.classnames
。
<init-param>
<param-name>jersey.config.server.provider.classnames</param-name>
<param-value>org.glassfish.jersey.Hymanson.HymansonFeature</param-value>
</init-param>
The MessageBodyWriter
provided by Hymanson is HymansonJsonProvider
. For more details on how to use Hymanson as a JSON provider, have a look at this answer. If you need to customize the ObjectMapper
, refer to this answer.
在MessageBodyWriter
Hyman逊提供的是HymansonJsonProvider
。有关如何使用 Hymanson 作为 JSON 提供程序的更多详细信息,请查看此答案。如果您需要自定义ObjectMapper
,请参阅此答案。
Fixing your resource class
修复你的资源类
By using the approach described above, you resource class can be as simple as:
通过使用上述方法,您的资源类可以很简单:
@Path("/users")
public class MyRestService {
@GET
@Produces({MediaType.APPLICATION_JSON + ";charset=UTF-8"})
public List<User> findUsers() {
List<User> users = new ArrayList<>();
users.add(new User("Nick", "admin", "32", 47));
return Response.ok(users).build();
}
When requesting such endpoint, it will give you the expected JSON as result.
当请求这样的端点时,它会给你预期的 JSON 结果。
回答by Bahadar Ali
I have also the same problem and tried different solutions, but non works. The problem is not with the mapper, but with the input to the mapper. As in your case: jsonInString = mapper.writeValueAsString(users);
'users' is a collection. You need to convert each user to JSONObject
, add it to JSONArray
and then use the mapper on the array: like this JSONArray users = new JSONArray();
for (Collection user : usersCollection) {
JSONObject user = new JSONObject(mapper.writeValueAsString(user));
users.put(user);
}
mapper.writeValueAsString(user));
我也有同样的问题并尝试了不同的解决方案,但不起作用。问题不在于映射器,而在于映射器的输入。与您的情况一样:jsonInString = mapper.writeValueAsString(users);
“用户”是一个集合。您需要将每个用户转换为JSONObject
,将其添加到JSONArray
然后在数组上使用映射器:像这样JSONArray users = new JSONArray();
for (Collection user : usersCollection) {
JSONObject user = new JSONObject(mapper.writeValueAsString(user));
users.put(user);
}
mapper.writeValueAsString(user));
回答by Sujan
It should not be a problem, just you need to parse it in javascript and use it : JSON.parse(response)
这应该不是问题,只是你需要在 javascript 中解析它并使用它: JSON.parse(response)
回答by Bob
If you are using Spring and the @ControllerAdvice for JSONP, then create a wrapper for the JSON string and use @JsonRawValue on the property. The JSONP @ControllerAdvice will not wrap a String response, it needs an Object.
如果您将 Spring 和 @ControllerAdvice 用于 JSONP,则为 JSON 字符串创建一个包装器并在属性上使用 @JsonRawValue。JSONP @ControllerAdvice 不会包装字符串响应,它需要一个对象。
public class JsonStringResponse {
@JsonValue
@JsonRawValue
private String value;
public JsonStringResponse(String value) {
this.value = value;
}
}
@GetMapping
public ResponseEntity<JsonStringResponse> getJson() {
String json = "{"id":2}";
return ResponseEntity.ok().body(new JsonStringResponse(json));
}
@ControllerAdvice
public class JsonpControllerAdvice extends AbstractJsonpResponseBodyAdvice {
public JsonpControllerAdvice() {
super("callback");
}
}
Response is a json object {"id":2}
If there is a callback parameter the response is callbackparameter({"id":2});
响应是一个 json 对象{"id":2}
如果有一个回调参数响应是callbackparameter({"id":2});
回答by Deepraj jha
Do this.
做这个。
ObjectMapper mapper = new ObjectMapper();
mapper.getFactory().setCharacterEscapes(new JsonUtil().new CustomCharacterEscapes());
ObjectWriter writer = mapper.writer();
String jsonDataObject = mapper.writeValueAsString(configMap);
public class CustomCharacterEscapes extends CharacterEscapes {
private final int[] _asciiEscapes;
public CustomCharacterEscapes() {
_asciiEscapes = standardAsciiEscapesForJSON();
//By default the ascii Escape table in Hymanson has " added as escape string
//overwriting that here.
_asciiEscapes['"'] = CharacterEscapes.ESCAPE_NONE;
}
@Override
public int[] getEscapeCodesForAscii() {
return _asciiEscapes;
}
@Override
public SerializableString getEscapeSequence(int i) {
return null;
}
}