JsonPath

JsonPath一套json解析和定位工具,通过表达式访问json元素。 例如 $.store.book[0].title$['store']['book'][0]['title'] 其中 $ 表示 json 根元素,点表示下级,方括号访问数组元素。

json-path / JsonPath https://github.com/json-path/JsonPath

JsonPath 在线验证 https://www.jsonpath.cn/


新增属性字段到已有json

在原始json rawJson 的 jsonPath 位置上,添加内容 content jsonPath 是一个原始 json 中不存在的字段

/**
 * 新增属性字段到已有json
 * @param rawJson 原始json
 * @param jsonPath 新字段的JsonPath
 * @param content 要添加的内容
 */
@SneakyThrows
private String insertValue(String rawJson, String jsonPath, Object content) {
    // Configuration ensuring addition of new leaves without raising exception
    Configuration conf = Configuration.defaultConfiguration()
                                        .addOptions(Option.DEFAULT_PATH_LEAF_TO_NULL)
                                        .addOptions(Option.SUPPRESS_EXCEPTIONS);
    DocumentContext documentContext = JsonPath.using(conf).parse(rawJson);
    documentContext.set(jsonPath, content);
    return documentContext.jsonString();
}

使用:

/**
 * 添加 List<String> errors 字段到第一个 book
 */
@Test
public void testAddPropertyToBookStoreJson() {
    String json = insertValue(getBookStoreJson(), "$.store.book[0].errors", Lists.newArrayList("aaaa", "bbbb"));
    log.info(JsonMappers.Normal.toPrettyJson(JsonMappers.Normal.fromJson(json, Object.class)));
}

Add key with array to json by path https://stackoverflow.com/questions/34330216/add-key-with-array-to-json-by-path