将json字符串转换为包含@key的POJO

时间:2016-08-09 03:37:29

标签: java json jackson pojo

我有一个json字符串,如下所示。

import functools

# Input
raw_data = [
    [2, 2, 3, 4, 5, 6, 7],
    [0, 2, 3, 4, 5, 6, 17],
    [3, 4, 3, 4, 5, 6, 37]
]

min_max_rows = list(map(lambda x: (min(x), max(x)), raw_data))
result = functools.reduce(lambda x, y: (min(x), max(y)), min_max_rows)

print(result) # Prints (2,37) instead of (0,37)

我想转换成类的POJO,如下所示。

{
    "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"
}

我正在尝试使用jackson将json转换为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;
}

当我运行代码时,我在pojo中获取所有空值,因为jackson正在查找json字符串中的属性名称而不是@key中给出的名称。如何告诉Jackson根据@Key映射值?

之前我使用过@JsonProperty并没有转换成pojo的问题。候选类由第三方提供,他们使用@key(com.google.api.client.util.Key)注释作为属性。所以,我无法改变课程。

2 个答案:

答案 0 :(得分:1)

使用此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);

答案 1 :(得分:0)

假设您无法更改类,您也可以使用GSON将其转换回Candidate类。我建议只使用 ,因为您无法更改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 Annotation和对象映射器的替代品,但是使用GSON,在这种情况下,你提供的源POJO几乎涵盖了

编辑你也可以使用JacksonFactory,如下所示

import com.google.api.client.json.jackson.JacksonFactory;

    Candidate candidate2 = new JacksonFactory().fromString(jsonInString, Candidate.class);

    System.out.println(candidate2);