json字段映射到bean:
@see:https:
json:
{"location":"广州","temp":15,"weather":"多云"}
{"place":"深圳","temperature":35,"outlook":"晴天"}
使用Jackson:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.8</version>
</dependenc>
示例:
bean代码:
@JsonProperty("location")
@JsonAlias({"place", "******"})
private String location;
@JsonProperty("temp")
@JsonAlias({"temperature", "******"})
private int temp;
@JsonProperty("outlook")
@JsonAlias({"weather", "******"})
private String outlook;
test:
ObjectMapper mapper = new ObjectMapper();
Weather weather = mapper.readValue("{"location": "广州","temp": 15,"weather": "多云"}", Weather.class);
使用Gson:
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.5</version>
<scope>test</scope>
</dependency>
示例:
bean代码:
@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:
Gson gson = new GsonBuilder().create();
Weather weather = gson.fromJson("{"location": "广州","temp": 15,"weather": "多云"}", Weather.class);