本文介绍了杰克逊解析json与unwraping root,但没有能力设置@JsonRootName的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

其他服务回复

<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
}

但实际上我应该使用交易来自第三方jar的类,与上面的类似,但没有@JsonRootName(transaction)注释。

But actually I should use the Transaction class from 3rd party jar, which is exact like above, but has no @JsonRootName("transaction") annotation.

所以我最终with

Could not read JSON: Root name 'transaction' does not match expected ('Transaction') for type...

有没有办法强制Jackson解析到Transaction类而不向Transaction类本身添加任何东西(如我把这个文件作为二进制jar的一部分)?

Is there any ways to force Jackson parse to Transaction class without adding any stuff to the Transaction class itself (as I get this file as part of a binary jar)?

我尝试过定制的PropertyNamingStrategy,但它似乎只能用字段和getter / setter名称来做,但是不是班级名称。

I've tried custom PropertyNamingStrategy, but it seems has to do only with field and getter/setter names, but not class names.

Java7,Jackson 2.0.5。

Java7, Jackson 2.0.5.

有什么建议吗?谢谢。

推荐答案

你可以用功能。您可以像这样创建简单的接口/抽象类:

You can do it with mixin feature. You can create simple interface/abstract class like this:

@JsonRootName("transaction")
interface TransactionMixIn {

}

现在,您必须配置 ObjectMapper object:

Now, you have to configure ObjectMapper object:

ObjectMapper mapper = new ObjectMapper();
mapper.enable(DeserializationFeature.UNWRAP_ROOT_VALUE);
mapper.addMixInAnnotations(Transaction.class, TransactionMixIn.class);

最后你可以用它来反序列化JSON:

And finally you can use it to deserialize JSON:

mapper.readValue(json, Transaction.class);

第二个选项 - 你可以写 Transaction class。

Second option - you can write custom deserializer for Transaction class.

这篇关于杰克逊解析json与unwraping root,但没有能力设置@JsonRootName的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-20 03:11