进入body方法时,对象“ info”应该具有另一个字段名称。例如brandName-> BrandName,id-> Id等。
@JsonRootName(value = "Laptop")
@XmlRootElement(name = "Laptop")
public class ComputerInfo {
@JacksonXmlProperty(isAttribute = true)
@SerializedName("BrandName")
private String brandName;
@JacksonXmlProperty(isAttribute = true)
@SerializedName("Id")
private String id;
@JacksonXmlProperty(isAttribute = true)
@SerializedName("LaptopName")
private String laptopName;
@JacksonXmlProperty(isAttribute = true)
@SerializedName("Features")
private Feature features;
@XmlElement(name = "BrandName")
public String getBrandName() {
return brandName;
}
@XmlElement(name = "Id")
public String getId() {
return id;
}
@XmlElement(name = "LaptopName")
public String getLaptopName() {
return laptopName;
}
@XmlElement(name = "Features")
public Feature getFeatures() {
return features;
}
public void setBrandName(String brandName) {
this.brandName = brandName;
}
public void setId(String id) {
this.id = id;
}
public void setLaptopName(String laptopName) {
this.laptopName = laptopName;
}
public void setFeatures(Feature features) {
this.features = features;
}
@Override
public String toString() {
return "ComputerInfo{" +
"brandName='" + brandName + '\'' +
", id='" + id + '\'' +
", laptopName='" + laptopName + '\'' +
", features=" + features +
'}';
}
}
public class Feature {
@JacksonXmlProperty(isAttribute = true)
@SerializedName("Feature")
private ArrayList<String> feature;
public ArrayList<String> getFeature() {
return feature;
}
public void setFeature(ArrayList<String> feature) {
this.feature = feature;
}
}
我的测试
@Test
public void testPostWithObjectMapping() throws URISyntaxException {
URI uri = new URI("http://localhost:8080/laptop-bag/webapi/api/add");
String id = new Random().nextInt(500) + "";
ComputerInfo info = new ComputerInfo();
info.setBrandName("Microsoft");
info.setId(id);
info.setLaptopName("Surface");
Feature feature = new Feature();
feature.setFeature(new ArrayList<>(Arrays.asList("8GB RAM", "1 TB Hard Drive")));
info.setFeatures(feature);
Response response = given().accept(ContentType.JSON)
.log()
.body()
.with()
.contentType(ContentType.JSON)
.body(info)
.post(uri);
response
.thenReturn()
.then()
.assertThat()
.statusCode(HttpStatus.SC_OK)
.body("Laptop.Id", equalTo( info.getId( )));
}
结果:
ComputerInfo {brandName ='Microsoft',id ='421',laptopName ='Surface',
features=http_client.models.Feature@cb51256}
但这应该是
Laptop{BrandName='Microsoft', Id='421', LaptopName='Surface', Features=""}
最佳答案
SerializedName
是Gson的注解,而不是Jackson的注解
您应该使用@JsonProperty("BrandName")
而不是@SerializedName("BrandName")