Reputation: 45
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.
Upvotes: 2
Views: 2283
Reputation: 4948
Assuming you are not able to change the class , you can use GSON as well to convert it back to Candidate class. I am suggesting this only because you cannot change the annotation in the POJO class that you have.
Gson gson = new Gson();
String jsonInString = "{\"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\"}";
Candidate candidate = gson.fromJson(jsonInString, Candidate.class);
System.out.println(candidate);
Although this is no replacement for the JACKSON Annotation and object mapper you have , using GSON you are covered pretty much in this case on the Source POJO provided
edit you can also use JacksonFactory as below
import com.google.api.client.json.jackson.JacksonFactory;
Candidate candidate2 = new JacksonFactory().fromString(jsonInString, Candidate.class);
System.out.println(candidate2);
Upvotes: 0
Reputation: 9406
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);
Upvotes: 1