How to Resolve Any JSON Node Using Jackson and JSON Pointer Queries
- 2021-11-14 05:33:25
- OfStack
Jackson and JSON Pointer queries resolve any JSON node
JSON Pointer is a string expression that identifies a specific node of an JSON document. The RFC 6901 specification is defined for querying complex Json document structures.
1. Sample Json document
{
"firstName": "John",
"lastName": "Doe",
"address": {
"street": "21 2nd Street",
"city": "New York",
"postalCode": "10021-3100",
"coordinates": {
"latitude": 40.7250387,
"longitude": -73.9932568
}
},
"phone": [
"139",
"137"
],
"grade": [
{
"name": "math",
"score": 99
},
{
"name": "english",
"score": 97
}
]
}
This document includes complex nesting, in which nested types are objects, arrays and array objects. The following is parsed using JSON Pointer.
2. Parse the document
Using ObjectMapper, the core object of Jackson, first parses the json string not JsonNode.
String json = "{\n" +
" \"firstName\": \"John\",\n" +
" \"lastName\": \"Doe\",\n" +
" \"address\": {\n" +
" \"street\": \"21 2nd Street\",\n" +
" \"city\": \"New York\",\n" +
" \"postalCode\": \"10021-3100\",\n" +
" \"coordinates\": {\n" +
" \"latitude\": 40.7250387,\n" +
" \"longitude\": -73.9932568\n" +
" }\n" +
" },\n" +
" \"phone\":[\"139\",\"137\"],\n" +
" \"grade\":[\n" +
" {\"name\":\"math\",\"score\":99},\n" +
" {\"name\":\"english\",\"score\":97}\n" +
" ]\n" +
" }";
ObjectMapper mapper = new ObjectMapper();
JsonNode node = mapper.readTree(json);
2.1 Getting Properties
JsonNode firstName = node.at("/firstName");
print("firstName",firstName.toString());
Must begin with/to indicate the current starting node.
Output:
firstName:"John"
2.2 Getting Object Properties
JsonNode coordinatesNode = node.at("/address/coordinates");
print("coordinatesNode",coordinatesNode.toString());
Output:
coordinatesNode:{"latitude":40.7250387,"longitude":-73.9932568}
2.3 Getting Array Attributes
JsonNode phoneNode = node.at("/phone");
print("phoneNode", phoneNode.toString());
Output:
phoneNode:["139","137"]
2.4 Get Array Attribute Elements
JsonNode phone1Node = node.at("/phone/0");
print("phone1Node",phone1Node.toString());
Output:
phone1Node:"139"
2.4 Getting Array Object Properties
JsonNode nameNode = node.at("/grade/0/name");
print("name",nameNode.toString());
JsonNode scoreNode = node.at("/grade/0/score");
print("score",scoreNode.toString());
Output:
name:"math"
score:99
Jackson General Analytical JSON Method
package com.util;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.type.TypeFactory;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* json Parsing class, common to all projects
* <p/>
* Created by Liu 1 Wave on 15/7/24.
* E-Mail:zhanlanstar@163.com
*/
@Slf4j
public class JsonUtils {
private static ObjectMapper objectMapper = new ObjectMapper();
static {
objectMapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);
objectMapper.configure(SerializationFeature.INDENT_OUTPUT, true);
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
objectMapper.setDateFormat(sdf);
}
/**
* Provide to elasticsearch Use, put bean Convert to list map Collection type, otherwise it cannot be stored in index
*
* @param o
* @return
*/
public static Object beanToJsonObject(Object o) {
return jsonStrToList(objectToJsonStr(o), Map.class);
}
public static String objectToJsonStr(Object o) {
try {
return objectMapper.writeValueAsString(o);
} catch (IOException e) {
log.error("object can not objectTranslate to json", e);
}
return null;
}
public static <T> T jsonStrToObject(String json, Class<T> cls) {
try {
return objectMapper.readValue(json, cls);
} catch (IOException e) {
log.error("json cant be objectTranslate to object", e);
return null;
}
}
public static <T> T jsonDataToObject(String jsonStr, Class<T> cls) {
if (!StringUtils.isEmpty(jsonStr)) {
T data = JsonUtils.jsonStrToObject(jsonStr, cls);
return data;
} else {
return null;
}
}
public static <T> List<T> jsonStrToList(String jsonStr, Class<?> clazz) {
List<T> list = Lists.newArrayList();
try {
// Specify the container structure and type (in this case, ArrayList And clazz )
TypeFactory t = TypeFactory.defaultInstance();
list = objectMapper.readValue(jsonStr,
t.constructCollectionType(ArrayList.class, clazz));
} catch (IOException e) {
log.error(" Deserialization serialization attributes , from Json To List Report an error ", e);
}
return list;
}
public static Map jsonStrToMap(String attributes) {
try {
return objectMapper.readValue(attributes, HashMap.class);
} catch (IOException e) {
log.error(" Deserialization serialization attributes , from Json To HashMap Report an error ", e);
}
return new HashMap();
}
}