作者热门文章
- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
其余服务响应
<transaction><trxNumber>1243654</trxNumber><type>INVOICE</type></transaction>
或在 JSON 中:
{"transaction":{"trxNumber":1243654,"type":"INVOICE"}}
我用的时候没有问题:
mapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true)
作为结果类
@JsonRootName("transaction")
public class Transaction {
private String trxNumber;
private String type;
//getters and setters
}
但实际上我应该使用第 3 方 jar 中的事务类,它与上面完全相同,但没有 @JsonRootName("transaction") 注释。
所以我最终得到了
Could not read JSON: Root name 'transaction' does not match expected ('Transaction') for type...
有什么方法可以强制 Jackson 解析为 Transaction 类而不向 Transaction 类本身添加任何内容(因为我将此文件作为二进制 jar 的一部分获取)?
我试过自定义 PropertyNamingStrategy,但它似乎只与字段和 getter/setter 名称有关,而不是类名称。
Java7, jackson 2.0.5。
有什么建议吗?谢谢。
最佳答案
您可以使用 mixin 来完成特征。您可以像这样创建简单的接口(interface)/抽象类:
@JsonRootName("transaction")
interface TransactionMixIn {
}
现在,您必须配置 ObjectMapper
对象:
ObjectMapper mapper = new ObjectMapper();
mapper.enable(DeserializationFeature.UNWRAP_ROOT_VALUE);
mapper.addMixInAnnotations(Transaction.class, TransactionMixIn.class);
最后你可以用它来反序列化 JSON:
mapper.readValue(json, Transaction.class);
第二个选项 - 你可以写 custom deserializer对于 Transaction
类。
关于java - Jackson 使用解包根解析 json,但无法设置 @JsonRootName,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19568867/
我是一名优秀的程序员,十分优秀!