Jackson parsed json with an unresponsive root, but without the ability to set @JsonRootName

The recreation service is in charge

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

or in JSON:

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

No problem using:

 mapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true) 

And as a final class

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

But in fact, I have to use the Transaction class from a third-party jar, which is exactly the same as above , but does not have the @JsonRootName ("transaction") annotation.

So, I end up being

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

Is there a way to get Jackson to parse the Transaction class without adding any material to the Transaction class (since I get this file as part of a binary jar)?

I tried a custom PropertyNamingStrategy, but it seems to deal only with field and getter / settings names, but not with class names.

Java7, Jackson 2.0.5.

Any suggestions? thanks.

+6
source share
1 answer

You can do this with mixin . You can create a simple interface / abstract class as follows:

 @JsonRootName("transaction") interface TransactionMixIn { } 

Now you need to configure the 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); 

The second option is to write a custom deserializer for the Transaction class.

+5
source

Source: https://habr.com/ru/post/956653/


All Articles