Eugene S
Eugene S

Reputation: 99

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

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.

Upvotes: 6

Views: 8528

Answers (1)

Michał Ziober
Michał Ziober

Reputation: 38710

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.

Upvotes: 5

Related Questions