gpt4 book ai didi

java - 当我将对象放入正文时,我得到不同的字段名称

转载 作者:行者123 更新时间:2023-12-02 09:50:04 25 4
gpt4 key购买 nike

对象“info”在进入主体方法时应该有另一个字段名称。例如品牌名称->品牌名称、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")

关于java - 当我将对象放入正文时,我得到不同的字段名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56381290/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com