【问题标题】:Jackson JsonRootName doesn't add any root valueJackson JsonRootName 不添加任何根值
【发布时间】:2020-07-11 23:11:53
【问题描述】:

我正在序列化一个对象,我想为其设置一个根值。

这是我的课。

@JsonRootName(value = "user")
public class User {
    @JsonProperty
    private String name;
    @JsonProperty
    private int id;

    public User(int id, String name) {
        this.name = name;
        this.id = id;
    }
}

这就是我序列化它的方式:

 public static void main(String[] args) throws JsonProcessingException {
        User user = new User(1, "foobar");
        ObjectMapper mapper = new ObjectMapper();
        String serilizedValue = mapper.writeValueAsString(user);
        System.out.println(serilizedValue);
    }

但序列化后的值为:

{"name":"foobar","id":1}

当我希望在类定义中得到一个根 json 值时。

你能帮忙吗?

【问题讨论】:

    标签: java jackson


    【解决方案1】:
    @JsonRootName(value = "user")
    public static class User {
            @JsonProperty
            private String name;
            @JsonProperty
            private int id;
    
            public User(int id, String name) {
                this.name = name;
                this.id = id;
            }
    }
    
    public static void main(String[] args) throws InterruptedException, ParseException, JsonProcessingException {
          User user = new User(1, "foobar");
          ObjectMapper mapper = new ObjectMapper();
          mapper.enable(SerializationFeature.WRAP_ROOT_VALUE);
          String serilizedValue = mapper.writeValueAsString(user);
          System.out.println(serilizedValue);
    }
    

    输出:

    {"user":{"name":"foobar","id":1}}
    

    您需要在对象映射器上启用WRAP_ROOT_VALUE

    【讨论】:

      猜你喜欢
      • 2016-07-06
      • 2021-03-02
      • 2019-06-27
      • 1970-01-01
      • 2016-05-10
      • 1970-01-01
      • 2015-09-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多