1. Overview
1.概述
This quick tutorial illustrates how to change the name of a field to map to another JSON property on serialization.
这个快速教程说明了如何在序列化时改变一个字段的名称以映射到另一个JSON属性。
If you want to dig deeper and learn other cool things you can do with the Jackson 2 – head on over to the main Jackson tutorial.
如果你想更深入地了解你可以用杰克逊2做的其他很酷的事情–请到杰克逊主要教程。
2. Change Name of Field for Serialization
2.改变序列化字段的名称
Working with a simple entity:
与一个简单的实体一起工作。
public class MyDto {
private String stringValue;
public MyDto() {
super();
}
public String getStringValue() {
return stringValue;
}
public void setStringValue(String stringValue) {
this.stringValue = stringValue;
}
}
Serializing it will result in the following JSON:
对它进行序列化将产生以下的JSON。
{"stringValue":"some value"}
To customize that output so that, instead of stringValue we get – for example – strVal, we need to simply annotate the getter:
为了定制该输出,使我们得到的不是stringValue,而是–例如–strVal,我们需要简单地注释一下getter:。
@JsonProperty("strVal")
public String getStringValue() {
return stringValue;
}
Now, on serialization, we will get the desired output:
现在,在序列化时,我们将得到期望的输出。
{"strVal":"some value"}
A simple unit test should verify the output is correct:
一个简单的单元测试应该验证输出是否正确。
@Test
public void givenNameOfFieldIsChanged_whenSerializing_thenCorrect()
throws JsonParseException, IOException {
ObjectMapper mapper = new ObjectMapper();
MyDtoFieldNameChanged dtoObject = new MyDtoFieldNameChanged();
dtoObject.setStringValue("a");
String dtoAsString = mapper.writeValueAsString(dtoObject);
assertThat(dtoAsString, not(containsString("stringValue")));
assertThat(dtoAsString, containsString("strVal"));
}
3. Conclusion
3.结论
Marshaling an entity to adhere to a specific JSON format is a common task – and this article shows how to do is simply by using the @JsonProperty annotation.
将实体打包成特定的JSON格式是一项常见的任务–本文展示了如何通过使用@JsonProperty注解来实现。
The implementation of all these examples and code snippets can be found in my github project.
所有这些例子和代码片段的实现都可以在我的github项目中找到。