Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jackson parse json with unwraping root, but without ability to set @JsonRootName

Tags:

java

json

jackson

The rest service responds with

<transaction><trxNumber>1243654</trxNumber><type>INVOICE</type></transaction>

or in JSON:

{"transaction":{"trxNumber":1243654,"type":"INVOICE"}}

There is no problems when I use:

mapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true)

And as resulting class

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

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

So I end up with

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

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)?

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.

Any suggestions? thanks.

like image 828
Eugene S Avatar asked Oct 24 '13 14:10

Eugene S


1 Answers

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

@JsonRootName("transaction")
interface TransactionMixIn {

}

Now, you have to configure ObjectMapper object:

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

And finally you can use it to deserialize JSON:

mapper.readValue(json, Transaction.class);

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

like image 176
Michał Ziober Avatar answered Oct 18 '22 18:10

Michał Ziober