java 如何将 JSON 字段映射到自定义对象属性?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29746303/
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
How to map JSON fields to custom object properties?
提问by membersound
I have a simple json
message with some fields, and want to map it to a java object using spring-web
.
我有一个json
包含一些字段的简单消息,并希望使用spring-web
.
Problem: my target classes fields are named differently than int he json response. How can I anyhow map them to the object without having to rename the fields in java?
问题:我的目标类字段的命名与 int he json 响应不同。我怎样才能将它们映射到对象而不必重命名 java 中的字段?
Is there some annotation that could be placed here?
是否有一些注释可以放在这里?
{
"message":"ok"
}
public class JsonEntity {
//how to map the "message" json to this property?
private String value;
}
RestTemplate rest = new RestTemplate();
rest.getForObject(url, JsonEntity.class);
回答by cн?dk
To map a JSON property to a java object with a different name use @JsonProperty annotation, and your code will be :
要将 JSON 属性映射到具有不同名称的 java 对象,请使用 @JsonProperty 注释,您的代码将是:
public class JsonEntity {
@JsonProperty(value="message")
private String value;
}
回答by kamil.rak
Try this:
试试这个:
@JsonProperty("message")
private String value;
回答by bhdrkn
In case you familiar it, you can also use Jaxb annotations to marshal/unmarshal json using Hymanson
如果您熟悉它,您还可以使用 Jaxb 注释来使用 Hymanson 编组/解组 json
@XmlRootElement
public class JsonEntity {
@XmlElement(name = "message")
private String value;
}
But you must initialize your Hymanson context propery. Here an example how to initialize Hymanson context with Jaxb annotations.
但是您必须初始化您的 Hymanson 上下文属性。这是一个如何使用 Jaxb 注释初始化 Hymanson 上下文的示例。
ObjectMapper mapper = new ObjectMapper();
AnnotationIntrospector introspector = new JaxbAnnotationIntrospector();
mapper.getDeserializationConfig().setAnnotationIntrospector(introspector);
mapper.getSerializationConfig().setAnnotationIntrospector(introspector);