【问题标题】:Ignore enclosing braces with JSON parser while serializing object in Java在 Java 中序列化对象时使用 JSON 解析器忽略大括号
【发布时间】:2022-01-31 03:15:27
【问题描述】:

我有以下课程:

@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
public class User {

    private String id;
    private List<Reference> references;
.....
}
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
public class Reference {

    @JacksonXmlProperty(isAttribute = true)
    private String ref;

    public Reference(final String ref) {
        this.ref = ref;
    }

    public Reference() { }

    public String getRef() {
        return ref;
    }

}

当序列化为 XML 时,格式符合预期,但当我尝试序列化为 JSON 时,我得到以下信息

"users" : [
  {
      "references" : [
      {
        "ref": "referenceID"
      }
    ]
  }
]

我需要它是:

"users" : [
  {
      "references" : [
        "referenceID"
    ]
  }
]

包含引用列表的大括号我需要在没有属性名称的情况下忽略它

【问题讨论】:

    标签: java json jackson jsonparser


    【解决方案1】:

    您可以在Reference 类中使用JsonValue 注释来注释ref 字段,该注释指示带注释的访问器的值将用作实例序列化的单个值

    @Data
    @JsonIgnoreProperties(ignoreUnknown = true)
    @JsonInclude(JsonInclude.Include.NON_NULL)
    public class Reference {
    
        @JacksonXmlProperty(isAttribute = true)
        @JsonValue //<-- the new annotation
        private String ref;
    
        public Reference(final String ref) {
            this.ref = ref;
        }
    
        public Reference() { }
    
        public String getRef() {
            return ref;
        }
    
    }
    
    User user = new User();
    user.setReferences(List.of(new Reference("referenceID")));
    //it prints {"references":["referenceID"]}
    System.out.println(jsonMapper.writeValueAsString(user));
    

    编辑:似乎JsonValue 注释使类的序列化无效,正如OP 所期望的那样;解决这个问题的一种方法是为Reference 类使用mixin 类,并在JsonValue 注释内放置,原来的Reference 类将保持不变:

    @Data
    public class MixInReference {
        @JsonValue
        private String ref;
    }
    
    
    ObjectMapper jsonMapper = new ObjectMapper();
    //Reference class is still the original class
    jsonMapper.addMixIn(Reference.class, MixInReference.class);
    ////it prints {"references":["referenceID"]}
    System.out.println(jsonMapper.writeValueAsString(user));
    

    【讨论】:

    • 它工作了,但我必须将它添加到 get 方法中,现在我遇到了 XML 解析器的问题,因为架构定义说它应该同时具有 所以验证失败,因为参考值不是属性
    • 我不确定您的问题,有一个 xml 架构并且由于 json 注释而验证失败?
    • 我需要能够使用相同的对象序列化为 JSON 和 XML,使用 XML 我按预期工作,每个引用都有 ref 值作为属性,例如&lt;reference ref="value"&gt;,现在在添加 @JsonValue 后,它适用于 JSON 序列化但不适用于 XML,ref 不是属性,它像 &lt;reference&gt;value&lt;/reference&gt; 一样被序列化,所以它失败了,因为它期待属性
    • @zepol 我现在明白了,我更新了我的代码来解决xml序列化问题。
    猜你喜欢
    • 1970-01-01
    • 2017-05-26
    • 1970-01-01
    • 2020-12-21
    • 2019-07-10
    • 2018-02-13
    • 1970-01-01
    • 2016-01-22
    • 2016-11-21
    相关资源
    最近更新 更多