是否可以使用Jackson库手动解析JSON?
即。我不想使用ObjectMapper
并将JSON转换为某个对象,而是希望从JSON中选择一些单独的属性,就像在XPath中一样:
例如,这是我的JSON:
{
"person": {
"name": "Eric",
"surname": "Ericsson",
"address" {
"city": "LA",
"street": "..."
}
}
}
所有我想要的只是获取Name和City,在这种情况下我不想引入2个新的Java类(Person
和Address
)并将它们与{{1一起使用但是我只是想在xPath中读取这些值:
伪代码:
ObjectMapper
答案 0 :(得分:3)
您可以使用the Jackson tree model和JsonNode#at(...)
方法将Json Pointer表达式作为参数。
以下是一个例子:
public class JacksonJsonPointer {
static final String JSON = "{"
+ " \"person\": {"
+ " \"name\": \"Eric\","
+ " \"surname\": \"Ericsson\","
+ " \"address\": {"
+ " \"city\": \"LA\","
+ " \"street\": \"...\""
+ " }"
+ " }"
+ "}";
public static void main(String[] args) throws IOException {
final ObjectMapper mapper = new ObjectMapper();
final JsonNode json = mapper.readTree(JSON);
System.out.println(json.at("/person/name"));
System.out.println(json.at("/person/address/city"));
}
}
输出:
"Eric"
"LA"
答案 1 :(得分:1)
是使用Json解析器可以解析你的Json,下面是一个示例你可以在jackson文档中找到更多
JsonParser jsonParser = new JsonFactory().createJsonParser(jsonStr);
while(jsonParser.nextToken() != JsonToken.END_OBJECT){
String name = jsonParser.getCurrentName();
if("name".equals(name)) {
jsonParser.nextToken();
System.out.println(jsonParser.getText());
}
if("surname".equals(name)) {
jsonParser.nextToken();
System.out.println(jsonParser.getText());
}
if("city".equals(name)) {
jsonParser.nextToken();
System.out.println(jsonParser.getText());
}
}