Jackson 使用解包根解析 json,但无法设置 @JsonRootName [英] Jackson parse json with unwraping root, but without ability to set @JsonRootName

查看:57
本文介绍了Jackson 使用解包根解析 json,但无法设置 @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
}

但实际上我应该使用 3rd 方 jar 中的 Transaction 类,这与上面完全一样,但没有 @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.

所以我结束了

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,杰克逊 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 对象:

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 类.

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

这篇关于Jackson 使用解包根解析 json,但无法设置 @JsonRootName的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆