我尝试使用Spring使用其他API调用,如下所示:
HttpHeaders headers = new HttpHeaders();
headers.add("Authorization", "Basic " + base64Creds);
HttpEntity<String> request = new HttpEntity<String>(headers);
RestTemplate restTemplate = new RestTemplate();
Item item = restTemplate.exchange(url, HttpMethod.GET, request, Item.class).getBody();
我从API获得的响应如下:
{
"item":[{
"itemname": "abc",
"qty":...
}]
}
Item类包含以下字段:
Class Item{
@JsonProperty("itemname")
String name;
@JsonProperty("qty")
int quantity;
// Getter / setter methods
}
我已经在字段中添加了JsonProperty注释,因为它们的名称与我从API获得的json不同。有了这个,我能够成功地反序列化api响应。
但是,当我尝试将Item类再次序列化为json时,字段名称是&#34; itemname&#34;和&#34;数量&#34;。是否有任何方法可以将这些保留为&#34; name&#34;和&#34;数量&#34;,但能够映射到API响应?
提前致谢。
答案 0 :(得分:8)
如果您只想以不同的形式进行序列化,可以这样做:
public static class Item {
private String name;
private int quantity;
@JsonProperty("name")
public String getName() {
return name;
}
@JsonProperty("itemname")
public void setName(String name) {
this.name = name;
}
@JsonProperty("quantity")
public int getQuantity() {
return quantity;
}
@JsonProperty("qty")
public void setQuantity(int quantity) {
this.quantity = quantity;
}
}
这将显示"{"itemname": "abc", "qty":10 }"
并撰写"{"name": "abc", "quantity":10 }"
。
但是有一个很大的缺点 - 你不能用"{"name": "abc", "quantity":10 }"
来阅读ObjectMapper
(这是更糟糕的解决办法)。
您可以使用2 ObjectMappers
而不是类Annotations使用Mixins来配置特定的反序列化
这就是你的Mixin的样子:
abstract public static class ItemMixin {
ItemMixin(@JsonProperty("itemname") String itemname, @JsonProperty("qty") int qty) { }
// note: could alternatively annotate fields "w" and "h" as well -- if so, would need to @JsonIgnore getters
@JsonProperty("itemname") abstract String getName(); // rename property
@JsonProperty("qty") abstract int getQuantity(); // rename property
}
以下是在ObjectMapper中添加Mixin的方法。
objectMapper.addMixIn(Item.class, ItemMixinA.class);
因此,如果使用Mixin ObjectMapper反序列化,并使用标准ObjectMapper进行序列化,则没有任何问题。
您可以为您的班级撰写自定义JsonDeserialization
。
对于几乎没有字段的类来说很容易,但随着字段数量的增加,复杂性会按比例增长。
答案 1 :(得分:1)
尝试使用@JsonAlias批注指定可用于反序列化对象的其他属性名称。可以从这里获取更多信息: https://fasterxml.github.io/jackson-annotations/javadoc/2.9/com/fasterxml/jackson/annotation/JsonAlias.html