本文中,教你們如何使用Jackson和Gson將不一樣的JSON字段映射到單個Java字段中。bash
爲了使用Jackson和Gson庫,咱們須要在POM中添加如下依賴項:app
<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文檔的網站。可是,它們的格式並未是一致的maven
{
"location": "廣州",
"temp": 15,
"weather": "多雲"
}
複製代碼
{
"place": "深圳",
"temperature": 35,
"outlook": "晴天"
}
複製代碼
咱們但願將這兩種格式反序列化爲同一個Java類,名爲 Weather:測試
爲實現這一目標,咱們將使用Jackson的@JsonProperty和@JsonAlias註釋。這兩個註解將幫助咱們把JSON屬性映射到同一Java字段。網站
首先,咱們將使用@JsonProperty註釋,以便讓Jackson知道要映射的JSON字段的名稱。在值@JsonProperty註解同時用於反序列化和序列化。ui
而後咱們能夠使用@JsonAlias註釋。所以,Jackson將知道JSON文檔中映射到Java字段的其餘字段的名稱。在用了@JsonAlias註釋的屬性用於反序列化。google
@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對象。spa
@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註釋中使用值和 備用參數。code
第一個將用做默認值,而第二個將用於指示咱們要映射的JSON字段的備用名稱:xml
@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對象。