choom choom - 4 months ago 18
JSON Question

convert json string into POJO containing @key

I have a json string as shown below.

{
"input_index": 0,
"candidate_index": 0,
"delivery_line_1": "5461 S Red Cliff Dr",
"last_line": "Salt Lake City UT 84123-5955",
"delivery_point_barcode": "841235955990"
}


I want to convert into POJO of class as shown below.

public class Candidate {

@Key("input_index")
private int inputIndex;

@Key("candidate_index")
private int candidateIndex;

@Key("addressee")
private String addressee;

@Key("delivery_line_1")
private String deliveryLine1;

@Key("delivery_line_2")
private String deliveryLine2;

@Key("last_line")
private String lastLine;

@Key("delivery_point_barcode")
private String deliveryPointBarcode;
}


I am trying to convert json to pojo using jackson as shown below.

ObjectMapper objectMapper = new ObjectMapper();

objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

Candidate candidate = objectMapper.readValue(jsonString,Candidate.class);


When I run the code I am getting all null values in pojo because jackson is looking for attribute name in the json string instead of name given in @key. How do tell Jackson to map values based on @Key?

I used @JsonProperty before and had no issue converting into pojo. The Candidate class is provided by third party and they are using @key(com.google.api.client.util.Key) annotation for attributes. So, I can't change the class.

Answer

Use this maven dep :

<dependency>
    <groupId>com.google.http-client</groupId>
    <artifactId>google-http-client-jackson</artifactId>
    <version>1.15.0-rc</version>
</dependency>

And convert like this :

Candidate candidate = JacksonFactory.getDefaultInstance().fromString(output,Candidate.class);