Java @JsonRootName 不能如我所愿

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24132884/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 10:21:57  来源:igfitidea点击:

@JsonRootName not work as I want

javajsonjaxbHymansonroot

提问by Auf

This is my FacilityDTO

这是我的 FacilityDTO

@JsonRootName("Facility")
@XmlAccessorType(XmlAccessType.NONE)
@XmlType(name = "Facility", propOrder = { "id", "name", "totalQuantity" })
public class FacilityDTO implements Serializable {

private static final long serialVersionUID = 1L;

@XmlElement(required = true)
private String id;
@XmlElement(required = true)
private String name;
@XmlElement(required = true)
private double totalQuantity;

public FacilityDTO() {
}

public FacilityDTO(Facility facility) {
    this.name = facility.getName();
    this.totalQuantity = facility.getTotalQuantity();
    this.id = facility.getId();
}// getters setter

This is my message body writer

这是我的消息正文作者

ByteArrayOutputStream out = new ByteArrayOutputStream();
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new Jdk7Module());
mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, true);
mapper.writeValue(out, object);
int bytesCount = out.size();
byte[] bytes = out.toByteArray();
entityStream.write(bytes);
entityStream.flush();

The output of JSON format is like thisenter image description here

JSON格式的输出是这样的在此处输入图片说明

My Questions are:

我的问题是:

  1. Why the results seem not correct? I was put @JsonRootName("Facility") and also enable the wrap root feature.
  2. Any part I miss?
  1. 为什么结果似乎不正确?我被放置了 @JsonRootName("Facility") 并启用了 wrap root 功能。
  2. 有我想念的部分吗?

采纳答案by PhiLho

See Hymanson JSON Deserialization with Root Element

请参阅带有根元素的 Hymanson JSON 反序列化

According to the above, you need to configure deserialization as follows: mapper.configure(DerializationFeature.UNWRAP_ROOT_VALUE, true);

根据以上,需要配置反序列化如下: mapper.configure(DerializationFeature.UNWRAP_ROOT_VALUE, true);