我有一个json字符串,如下所示。
{
"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"
}
我想转换成如下所示的POJO类。
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;
}
我正在尝试使用jackson将json转换为pojo,如下所示。
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
Candidate candidate = objectMapper.readValue(jsonString,Candidate.class);
当我运行代码时,我在pojo中得到所有空值,因为jackson在json字符串中寻找属性名,而不是@key中给出的名称。如何告诉Jackson基于@Key映射值?
我以前使用过@JsonProperty,转换成pojo没有问题。候选类由第三方提供,他们使用@ key(com . Google . API . client . util . key)注释作为属性。所以,我不能换课。
使用此maven dep:
<dependency>
<groupId>com.google.http-client</groupId>
<artifactId>google-http-client-jackson</artifactId>
<version>1.15.0-rc</version>
</dependency>
并像这样转换:
Candidate candidate = JacksonFactory.getDefaultInstance().fromString(output,Candidate.class);
假设您无法更改类,您也可以使用GSON将其转换回候选类。我之所以建议这样做,只是因为您无法更改您拥有的 POJO 类中的注释。
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);
虽然这并不能取代JACKSON注释和对象映射器,但在本例中,使用GSON,您可以在提供的源POJO中看到很多内容
编辑你也可以使用JacksonFactory如下
import com.google.api.client.json.jackson.JacksonFactory;
Candidate candidate2 = new JacksonFactory().fromString(jsonInString, Candidate.class);
System.out.println(candidate2);