杰克逊在json中添加了反斜杠 [英] Jackson adds backslash in json

查看:188
本文介绍了杰克逊在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}]

很明显,杰克逊以某种方式逃脱了结果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 7 Jackson 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?

推荐答案

java中的所有字符串都必须在其中转义引号。所以jsonInString应该有斜杠。当你输出jsonInString虽然它不应该有引号。你是在调试器中看它吗?

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?

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

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