杰克逊解析json与unwraping root,但没有能力设置@JsonRootName

Eug*_*e S 6 java json jackson

休息服务回应

<transaction><trxNumber>1243654</trxNumber><type>INVOICE</type></transaction>
Run Code Online (Sandbox Code Playgroud)

或者在JSON中:

{"transaction":{"trxNumber":1243654,"type":"INVOICE"}}
Run Code Online (Sandbox Code Playgroud)

使用时没有问题:

mapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true)
Run Code Online (Sandbox Code Playgroud)

并由此产生的课程

@JsonRootName("transaction")
public class Transaction {
private String trxNumber;
private String type;
//getters and setters
}
Run Code Online (Sandbox Code Playgroud)

但实际上我应该使用第三方jar中的Transaction类,这与上面的完全一样,但没有@JsonRootName("transaction")注释.

所以我最终得到了

Could not read JSON: Root name 'transaction' does not match expected ('Transaction') for type...
Run Code Online (Sandbox Code Playgroud)

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

我尝试过自定义PropertyNamingStrategy,但似乎只能使用字段和getter/setter名称,而不是类名.

Java7,Jackson 2.0.5.

有什么建议?谢谢.

Mic*_*ber 5

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

@JsonRootName("transaction")
interface TransactionMixIn {

}
Run Code Online (Sandbox Code Playgroud)

现在,您必须配置ObjectMapper对象:

ObjectMapper mapper = new ObjectMapper();
mapper.enable(DeserializationFeature.UNWRAP_ROOT_VALUE);
mapper.addMixInAnnotations(Transaction.class, TransactionMixIn.class);
Run Code Online (Sandbox Code Playgroud)

最后,您可以使用它来反序列化JSON:

mapper.readValue(json, Transaction.class);
Run Code Online (Sandbox Code Playgroud)

第二个选项 - 您可以为类编写自定义反序列化程序Transaction.