如何使用杰克逊将JSON的一部分作为纯文本获取 [英] How to get a part of JSON as a plain text using Jackson
问题描述
我从API获得以下JSON:
I've got a following JSON from API:
"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"
.
I'm using Jackson library to deserialize this JSON to Java object. I don't want to create a special class for checkin_checkout_times
object. I just want to get it as a plain text. Like this "checkin_from": "14:00", "checkin_to": "00:00", "checkout_from": "", "checkout_to": "12:00"
.
在我的hotel_data
POJO中,该checkin_checkout_times
应该作为字符串,即:
In my POJO for hotel_data
this checkin_checkout_times
should be as a string i.e.:
@JsonProperty("checkin_checkout_times")
private String checkinCheckoutTimes
是否可以将JSON的这一部分作为纯文本获取?
Is this possible to get this part of the JSON as a plain text?
编辑:我收到com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of java.lang.String out of START_OBJECT token
at [Source: (String)...
Error that I'm getting com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of java.lang.String out of START_OBJECT token
at [Source: (String)...
推荐答案
使用JsonNode
.
只需对hotel_data
的POJO中的字段checkinCheckoutTimes
进行以下操作setter
,它便会为您工作.
Just make the following setter
for the field checkinCheckoutTimes
in your POJO for hotel_data
and it should work for you.
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}'}
这篇关于如何使用杰克逊将JSON的一部分作为纯文本获取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!