我使用的是jayway库,因为我必须使用JSONPath表达式。
{
"fruit":"Apple",
"size":"Large",
"price":"40"
}
上面是我的json,现在从这个JSON开始,假设我想从一个特定的路径中阅读。对于Ex:- $.fruit,所以代码片段将类似于假设我已经读取了json文件,并且在将它转换为string后存储在这里。
String sb ="input json";
DocumentContext context = JsonPath.parse(sb);
Object rawData = context.read(path);
考虑到这将给我字符串,因为它是明确的路径。我会让"Apple"存储在"sb"中
现在,如果我想将这个字符串值添加到一个不同的JSON中,它将只包含这个元素,该怎么办?使用jayway库类。
{
"fruit":"Apple"
}
我尝试了elements.
发布于 2022-09-29 01:47:12
简短的回答:在新的上下文中使用context.put
,而不是context.set
。
详细信息:
如果您想要创建一个包含{"fruit":"Apple"}
的新JSON对象,您可以选择起点并按如下方式扩展它:
String sb = " { \"fruit\":\"Apple\", \"size\":\"Large\", \"price\":\"40\" }";
DocumentContext context = JsonPath.parse(sb);
String key = "fruit";
Object rawData = context.read("$." + key);
// create a new context containing an empty JSON object:
DocumentContext context2 = JsonPath.parse("{}");
// add your JSON to the root of the object:
context2.put("$", key, rawData);
// print the result:
System.out.println(context2.jsonString());
这将产生以下结果:
{"fruit":"Apple"}
我不知道有一个路径运算符,它的意思是“所有东西,除了”你想要保留的东西。如果您想这样做,也许您必须迭代原始的JSON并删除不等于要保存的数据的每个对象。
发布于 2022-09-29 02:15:35
您可以考虑另一个库Josson,以获得更简单的语法。
https://github.com/octomix/josson
Josson josson = Josson.fromJsonString("{\"fruit\":\"Apple\", \"size\":\"Large\", \"price\":\"40\"}");
JsonNode node = josson.getNode("map(fruit)");
System.out.println(node.toPrettyString());
输出
{
"fruit" : "Apple"
}
https://stackoverflow.com/questions/73888132
复制相似问题