This question already has an answer here:
这个问题已经有了答案:
- How to map JSON field names to different object field names? 1 answer
- 如何将JSON字段名映射到不同的对象字段名?1回答
I have a simple json
message with some fields, and want to map it to a java object using spring-web
.
我有一条带有一些字段的简单json消息,希望使用spring-web将其映射到java对象。
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);
3 个解决方案
#1
9
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;
}
#2
2
Try this:
试试这个:
@JsonProperty("message")
private String value;
#3
1
In case you familiar it, you can also use Jaxb annotations to marshal/unmarshal json using Jackson
如果您熟悉它,还可以使用Jaxb注释使用Jackson对json进行编组/取消编组
@XmlRootElement
public class JsonEntity {
@XmlElement(name = "message")
private String value;
}
But you must initialize your Jackson context propery. Here an example how to initialize Jackson context with Jaxb annotations.
但是必须初始化Jackson上下文属性。这里有一个如何使用Jaxb注释初始化Jackson上下文的示例。
ObjectMapper mapper = new ObjectMapper();
AnnotationIntrospector introspector = new JaxbAnnotationIntrospector();
mapper.getDeserializationConfig().setAnnotationIntrospector(introspector);
mapper.getSerializationConfig().setAnnotationIntrospector(introspector);
#1
9
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;
}
#2
2
Try this:
试试这个:
@JsonProperty("message")
private String value;
#3
1
In case you familiar it, you can also use Jaxb annotations to marshal/unmarshal json using Jackson
如果您熟悉它,还可以使用Jaxb注释使用Jackson对json进行编组/取消编组
@XmlRootElement
public class JsonEntity {
@XmlElement(name = "message")
private String value;
}
But you must initialize your Jackson context propery. Here an example how to initialize Jackson context with Jaxb annotations.
但是必须初始化Jackson上下文属性。这里有一个如何使用Jaxb注释初始化Jackson上下文的示例。
ObjectMapper mapper = new ObjectMapper();
AnnotationIntrospector introspector = new JaxbAnnotationIntrospector();
mapper.getDeserializationConfig().setAnnotationIntrospector(introspector);
mapper.getSerializationConfig().setAnnotationIntrospector(introspector);