1.概述
如何同时使用Jackson将不同的JSON字段映射到单个Java字段。
2.JSON样例
假设要在Java应用程序中获取不同位置的天气详细信息。 找到了几个将天气数据发布为JSON文档的网站。 但是,它们使用略有不同的格式:
json1
{
"location": "beijing",
"temp": 15,
"weather": "Cloudy"
}
json2
{
"place": "xian",
"temperature": 35,
"outlook": "Sunny"
}
将这两种格式反序列化为同一个Java类,命名为Weather:
@Data
public class Weather {
private String location;
private int temp;
private String outlook;
}
3.使用Jackson
可以使用Jackson的@JsonProperty和@JsonAlias注解。 这些将能够将多个JSON属性映射到同一Java字段。
首先,使用@JsonProperty注解,以便Jackson知道要映射的JSON字段的名称。 @JsonProperty注解中的值用于反序列化和序列化。
以使用@JsonAlias批注。 Jackson知道JSON文档中映射到Java字段的其他字段的名称。 @JsonAlias注解中的值仅用于反序列化:
@Data
public class Weather {
@JsonProperty("location")
@JsonAlias(value = {
"place", "aa"})
private String location;
@JsonProperty("temp")
@JsonAlias(value = {
"temperature", "bb"})
private int temp;
@JsonProperty("outlook")
@JsonAlias(value = {
"weather", "cc"})
private String outlook;
}
测试代码:
@Test
public void test29() throws Exception {
ObjectMapper mapper = new ObjectMapper();
Weather weather = mapper.readValue("{\n"
+ " \"location\": \"beijing\",\n"
+ " \"temp\": 15,\n"
+ " \"weather\": \"Cloudy\"\n"
+ "}", Weather.class);
System.out.println(weather);//Weather(location=beijing, temp=15, outlook=Cloudy)
weather = mapper.readValue("{\n"
+ " \"place\": \"xian\",\n"
+ " \"temperature\": 35,\n"
+ " \"outlook\": \"Sunny\"\n"
+ "}", Weather.class);
System.out.println(weather);//Weather(location=xian, temp=35, outlook=Sunny)
weather = mapper.readValue("{\n"
+ " \"aa\": \"chengdu\",\n"
+ " \"bb\": -10,\n"
+ " \"cc\": \"cool\"\n"
+ "}", Weather.class);
System.out.println(weather);//Weather(location=chengdu, temp=-10, outlook=cool)
}