如何使用杰克逊

时间:2018-08-24 07:20:08

标签: java json jackson deserialization

我从API获得以下JSON:

    "hotel_data": {
        "name": "Hotel Name",
        "checkin_checkout_times": {
            "checkin_from": "14:00",
            "checkin_to": "00:00",
            "checkout_from": "",
            "checkout_to": "12:00"
        },
        "default_language": "en",
        "country": "us",
        "currency": "USD",
        "city": "Miami"
    }

我正在使用Jackson库将此JSON反序列化为Java对象。我不想为checkin_checkout_times对象创建一个特殊的类。我只是想以纯文本形式获得它。像这样"checkin_from": "14:00", "checkin_to": "00:00", "checkout_from": "", "checkout_to": "12:00"

在我的hotel_data POJO中,此checkin_checkout_times应该作为字符串,即:

    @JsonProperty("checkin_checkout_times")
    private String checkinCheckoutTimes

是否可以将JSON的这一部分作为纯文本获取?

编辑:我收到com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of java.lang.String out of START_OBJECT token at [Source: (String)...

的错误

2 个答案:

答案 0 :(得分:4)

使用JsonNode

只需在setter的POJO中为字段checkinCheckoutTimes输入以下hotel_data,它就可以为您工作。

public void setCheckinCheckoutTimes(JsonNode node) {
    this.checkinCheckoutTimes = node.toString();
}

示例

String str = "{ \"id\": 1, \"data\": { \"a\": 1 } }";
try {
    System.out.println(new ObjectMapper().readValue(str,Employee.class));
} catch (IOException e) {
    e.printStackTrace();
}

Employee如下:

class Employee
{
    private int id;
    private String data;

    public Employee() {
    }

    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }

    public String getData() {
        return data;
    }

    public void setData(JsonNode node) {
        this.data = node.toString();
    }

    @Override
    public String toString() {
        return "Employee{" +
                "id=" + id +
                ", data='" + data + '\'' +
                '}';
    }
}

给出以下输出:

Employee{id=1, data='{"a":1}'}

答案 1 :(得分:3)

您还可以按照the article中的描述编写自定义解串器:

public class RawJsonDeserializer extends JsonDeserializer<String> {

    @Override
    public String deserialize(JsonParser jp, DeserializationContext ctxt)
           throws IOException, JsonProcessingException {

        ObjectMapper mapper = (ObjectMapper) jp.getCodec();
        JsonNode node = mapper.readTree(jp);
        return mapper.writeValueAsString(node);
    }
}

,然后在班级中将其与注释一起使用:

public class HotelData {

    @JsonProperty("checkin_checkout_times")
    @JsonDeserialize(using = RawJsonDeserializer.class)
    private String checkinCheckoutTimes;

    // other attributes

    // getters and setters
}
相关问题