本文中,教你们如何使用Jackson和Gson将不一样的JSON字段映射到单个Java字段中。bash
为了使用Jackson和Gson库,咱们须要在POM中添加如下依赖项:markdown
<dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.8.5</version> <scope>test</scope> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.9.8</version> <scope>test</scope> </dependency> 复制代码
假如,咱们但愿将不一样位置的天气细节输入到咱们的Java类中。咱们发现了一些将天气数据发布为JSON文档的网站。可是,它们的格式并未是一致的app
{ "location": "广州", "temp": 15, "weather": "多云" } 复制代码
{ "place": "深圳", "temperature": 35, "outlook": "晴天" } 复制代码
咱们但愿将这两种格式反序列化为同一个Java类,名为 Weather:maven
为实现这一目标,咱们将使用Jackson的@JsonProperty和@JsonAlias注释。这两个注解将帮助咱们把JSON属性映射到同一Java字段。oop
首先,咱们将使用@JsonProperty注释,以便让Jackson知道要映射的JSON字段的名称。在值@JsonProperty注解同时用于反序列化和序列化。测试
而后咱们能够使用@JsonAlias注释。所以,Jackson将知道JSON文档中映射到Java字段的其余字段的名称。在用了@JsonAlias注释的属性用于反序列化。网站
@JsonProperty("location") @JsonAlias("place") private String location; @JsonProperty("temp") @JsonAlias("temperature") private int temp; @JsonProperty("outlook") @JsonAlias("weather") private String outlook; Getter、Setter忽略 复制代码
如今咱们已经添加了注释,让咱们使用Jackson的ObjectMapper方法建立Weather对象。ui
@Test public void test() throws Exception { ObjectMapper mapper = new ObjectMapper(); Weather weather = mapper.readValue("{\n" + " \"location\": \"广州\",\n" + " \"temp\": 15,\n" + " \"weather\": \"多云\"\n" + "}", Weather.class); TestCase.assertEquals("广州", weather.getLocation()); TestCase.assertEquals("多云", weather.getOutlook()); TestCase.assertEquals(15, weather.getTemp()); weather = mapper.readValue("{\n" + " \"place\": \"深圳\",\n" + " \"temperature\": 35,\n" + " \"outlook\": \"晴天\"\n" + "}", Weather.class); TestCase.assertEquals("深圳", weather.getLocation()); TestCase.assertEquals("晴天", weather.getOutlook()); TestCase.assertEquals(35, weather.getTemp()); } 复制代码
如今,咱们来看看Gson如何实现。咱们须要在@SerializedName注释中使用值和 备用参数。google
第一个将用做默认值,而第二个将用于指示咱们要映射的JSON字段的备用名称:spa
@SerializedName(value="location", alternate="place") private String location; @SerializedName(value="temp", alternate="temperature") private int temp; @SerializedName(value="outlook", alternate="weather") private String outlook; 复制代码
如今咱们已经添加了注释,让咱们测试一下咱们的例子:
@Test public void test() throws Exception { Gson gson = new GsonBuilder().create(); Weather weather = gson.fromJson("{\n" + " \"location\": \"广州\",\n" + " \"temp\": 15,\n" + " \"weather\": \"多云\"\n" + "}", Weather.class); TestCase.assertEquals("广州", weather.getLocation()); TestCase.assertEquals("多云", weather.getOutlook()); TestCase.assertEquals(15, weather.getTemp()); weather = gson.fromJson("{\n" + " \"place\": \"深圳\",\n" + " \"temperature\": 35,\n" + " \"outlook\": \"晴天\"\n" + "}", Weather.class); TestCase.assertEquals("深圳", weather.getLocation()); TestCase.assertEquals("晴天", weather.getOutlook()); TestCase.assertEquals(35, weather.getTemp()); } 复制代码
咱们经过使用Jackson的@JsonAlias或Gson的替代参数看到了这一点,咱们能够轻松地将不一样的JSON格式转换为相同的Java对象。