杰克逊在 json 中添加反斜杠

Jackson adds backslash in json(杰克逊在 json 中添加反斜杠)

本文介绍了杰克逊在 json 中添加反斜杠的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在 Jersey 上构建 REST 服务,并使用 Jackson 从我的模型的 java 类生成 JSON.具有绝对简单值的模型,我认为这是最典型的情况.但我得到了奇怪的结果:

I'm building REST service on Jersey and using Jackson 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:

[{"name":"Nick","role":"admin","age":"32","rating":47}]

我的预期结果:

[{"name":"Nick","role":"admin","age":"32","rating":47}]

我的字段源值不包含任何特殊字符.这些都是简单的词.

My source values of fields does NOT contains any special characters. These are simple words.

这是我的 Java 类.实体:

There're my Java classes. Entity:

public class User {

  private String name;

  private String role;

  private String age;

  private Integer rating;

休息服务等级:

@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;
}

我已经尝试使用注解 @JsonRawValue 作为字符串属性:

I've tried to use annotation @JsonRawValue for string properties:

@JsonRawValue
private String name;

但这种情况下的结果是:

But result in this case was:

[{"name":Nick,"role":admin,"age":32,"rating":47}]

我期望:

[{"name":"Nick","role":"admin","age":"32","rating":47}]

很明显,Jackson 以某种方式逃避了响应结果 json 中的引号.但它为什么会这样做,最重要的是如何避免呢?它们本身只是字符串!没有任何引号或特殊字符.

It's obvious that Jackson 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.

我使用 Java 7Jackson 2.6.1.和 Postman 来测试结果.有什么想法可以解决我的问题吗?

I use Java 7 and Jackson 2.6.1. And Postman to test result. Any ideas for fix of my problem?

推荐答案

看起来你的 JAX-RS 资源类过于复杂了.

Looks like you are over complicating your JAX-RS resource class.

要将 Jackson 用作 Jersey 2.x 的 JSON 提供程序,您无需创建 ObjectMapper 这样的实例.有更好的方法来实现它.继续阅读以了解更多详情.

To use Jackson 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.

要将 Jackson 2.x 用作 JSON 提供程序,您需要添加 jersey-media-json-jackson 模块到您的 pom.xml 文件:

To use Jackson 2.x as your JSON provider you need to add jersey-media-json-jackson module to your pom.xml file:

<dependency>
    <groupId>org.glassfish.jersey.media</groupId>
    <artifactId>jersey-media-json-jackson</artifactId>
    <version>2.25.1</version>
</dependency>

注册 Jackson 模块

然后注册JacksonFeature 在您的 应用程序/ResourceConfig 子类:

@ApplicationPath("/api")
public class MyApplication extends Application {

    @Override
    public Set<Class<?>> getClasses() {
        Set<Class<?>> classes = new HashSet<Class<?>>();
        classes.add(JacksonFeature.class);
        return classes;
    }
}

@ApplicationPath("/api")
public class MyApplication extends ResourceConfig {

    public MyApplication() {
        register(JacksonFeature.class);
    }
}

如果您没有 应用程序/ResourceConfig 子类,可以注册 JacksonFeature 在您的 web.xml 部署描述符中.可以在 逗号分隔值 中提供特定的资源、提供者和功能完全限定的类名jersey/org/glassfish/jersey/server/ServerProperties.html#PROVIDER_CLASSNAMES" rel="nofollow noreferrer">jersey.config.server.provider.classnames 初始化参数.

If you don't have an Application / ResourceConfig subclass, you can register the JacksonFeature in your web.xml deployment descriptor. The specific resource, provider and feature fully-qualified class names can be provided in a comma-separated value of jersey.config.server.provider.classnames initialization parameter.

<init-param>
    <param-name>jersey.config.server.provider.classnames</param-name>
    <param-value>org.glassfish.jersey.jackson.JacksonFeature</param-value>
</init-param>

MessageBodyWriter 是 JacksonJsonProvider.有关如何将 Jackson 用作 JSON 提供程序的更多详细信息,请查看此答案.如果需要自定义ObjectMapper,参考这个答案.

通过使用上述方法,您的资源类可以很简单:

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();
}

当请求此类端点时,它将为您提供预期的 JSON 作为结果.

When requesting such endpoint, it will give you the expected JSON as result.

这篇关于杰克逊在 json 中添加反斜杠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:杰克逊在 json 中添加反斜杠

基础教程推荐