我正在编写一个 Web 服务(服务器 + 客户端)。我能够提供服务并返回以下 json
{
"cities": {
"city": [
{
"name": "New Delhi",
"population": "19M",
"telephonecode": "011"
},
{
"name": "Mumbai",
"population": "21M",
"telephonecode": "022"
},
{
"name": "Chennai",
"population": "10M",
"telephonecode": "044"
}
]
}
}
我的 POJO 是
@XmlRootElement(name = "cities")
public class RestFulCities {
List<RestFulCity> restFulCityList;
@XmlElement(name = "city")
public List<RestFulCity> getRestFulCityList() {
return restFulCityList;
}
public void setRestFulCityList(List<RestFulCity> restFulCityList) {
this.restFulCityList = restFulCityList;
}
}
@XmlRootElement(name = "city")
public class RestFulCity {
private String name;
private String telephonecode;
private String population;
public RestFulCity(String name, String telephonecode, String population) {
this.name = name;
this.telephonecode = telephonecode;
this.population = population;
}
public RestFulCity(City city) {
this.name = city.getName();
this.telephonecode = city.getTelephonecode();
this.population = city.getPopulation();
}
@XmlElement
public String getName() {
return name;
}
@XmlElement
public String getTelephonecode() {
return telephonecode;
}
@XmlElement
public String getPopulation() {
return population;
}
}
现在我想编写一个客户端,它将这个 json 映射到我的 POJO,以便我得到一个用 java 填充的 RestFulCities 对象
我的客户代码如下:
public class Client {
static final String REST_URI = "http://localhost:8080/springrest/rest/";
static final String CITIES = "cities";
public static void main(String[] args) {
String s = "";
WebClient plainAddClient = WebClient.create(REST_URI);
plainAddClient.path(CITIES).accept("application/json");
s = plainAddClient.get(String.class);
try {
RestFulCities citiesObject = new ObjectMapper().readValue(s, RestFulCities.class);
for(RestFulCity city : citiesObject.getRestFulCityList()) {
System.out.println("----------START---------");
System.out.println(city.getName());
System.out.println(city.getPopulation());
System.out.println(city.getTelephonecode());
System.out.println("---------END----------");
}
} catch (JsonParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JsonMappingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
但问题是:我收到以下异常
org.codehaus.jackson.map.exc.UnrecognizedPropertyException: Unrecognized field "cities"(Class com.techartifact.example.spring.model.RestFulCities), not marked as ignorable
at [Source: java.io.StringReader@1d35bf2; line: 1, column: 12] (through reference chain: com.techartifact.example.spring.model.RestFulCities["cities"])
当我使用以下属性时:
@JsonIgnoreProperties(ignoreUnknown = true)
虽然我没有得到异常,但我的restFulCityList 是 null这是不希望的
请帮忙