- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在使用 JSON 并面临一些问题。
我想在 JSON 对象中插入/更新路径。在路径不存在的情况下,它将被创建,然后我插入一个新值。如果它退出,它将被一个新值更新
例如,我想添加这样的新路径:
val doc = JsonPath.parse(jsonString)
doc.add("$.user.name", "John")
class com.jayway.jsonpath.PathNotFoundException : Missing property in path $['user']
jsonString
不会改变:
var jsonString = "{}" val conf = Configuration.defaultConfiguration().addOptions(Option.DEFAULT_PATH_LEAF_TO_NULL).addOptions(Option.SUPPRESS_EXCEPTIONS)
JsonPath.using(conf).parse(jsonString).set(JsonPath.compile("$.user.name"), "John")
Log.d("TAG", "new json = $jsonString")
最佳答案
我尝试了三种不同的 JSON 库,支持 JsonPath/JsonPointer(Jackson、JsonPath 和 JSON-P),但它们都无法在缺少父节点的情况下重建 JSON 对象层次结构。所以我想出了我自己的解决方案,使用 Jackson/JsonPointer 向 JSON 对象添加新值,因为它允许浏览 JsonPointer 部分。
private static final ObjectMapper mapper = new ObjectMapper();
public void setJsonPointerValue(ObjectNode node, JsonPointer pointer, JsonNode value) {
JsonPointer parentPointer = pointer.head();
JsonNode parentNode = node.at(parentPointer);
String fieldName = pointer.last().toString().substring(1);
if (parentNode.isMissingNode() || parentNode.isNull()) {
parentNode = StringUtils.isNumeric(fieldName) ? mapper.createArrayNode() : mapper.createObjectNode();
setJsonPointerValue(parentPointer, parentNode); // recursively reconstruct hierarchy
}
if (parentNode.isArray()) {
ArrayNode arrayNode = (ArrayNode) parentNode;
int index = Integer.valueOf(fieldName);
// expand array in case index is greater than array size (like JavaScript does)
for (int i = arrayNode.size(); i <= index; i++) {
arrayNode.addNull();
}
arrayNode.set(index, value);
} else if (parentNode.isObject()) {
((ObjectNode) parentNode).set(fieldName, value);
} else {
throw new IllegalArgumentException("`" + fieldName + "` can't be set for parent node `"
+ parentPointer + "` because parent is not a container but " + parentNode.getNodeType().name());
}
}
ObjectNode rootNode = mapper.createObjectNode();
setJsonPointerValue(rootNode, JsonPointer.compile("/root/array/0/name"), new TextNode("John"));
setJsonPointerValue(rootNode, JsonPointer.compile("/root/array/0/age"), new IntNode(17));
setJsonPointerValue(rootNode, JsonPointer.compile("/root/array/4"), new IntNode(12));
setJsonPointerValue(rootNode, JsonPointer.compile("/root/object/num"), new IntNode(81));
setJsonPointerValue(rootNode, JsonPointer.compile("/root/object/str"), new TextNode("text"));
setJsonPointerValue(rootNode, JsonPointer.compile("/descr"), new TextNode("description"));
System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(rootNode));
{
"root" : {
"array" : [ {
"name" : "John",
"age" : 17
}, null, null, null, 12 ],
"object" : {
"num" : 81,
"str" : "text"
}
},
"descr" : "description"
}
关于java - 如何使用 JsonPath 向 Json 添加新节点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51971642/
我想添加一个监视器来检测不健康的服务并在这种情况下发送警报。我公开了一个简单的 REST API - /healthy,它返回一个 JSON例如{“健康”:true}。 然后我向我的 site24x7
使用 JSONPath,如何从已知键列表中提取单个值? 例如,我想编写一个 JSON 路径表达式,可以从所有这三个 JSON 文档中提取 Sean: { "firstName": "Sean"} {
使用节点 JSONPath,如何从子节点值中获取父节点名称 { "store": { "book": [ { "id":"1", "author
使用ashphy json path evaluator ,以及以下 JSON: { "store": { "book": [ { "category": "reference",
JsonPath 是否支持 AND (&&) 运算符? 考虑以下 JsonPath 表达式: $.values[?(@.level=='First' && @.type == 'Sales')].se
我正在尝试使用 jsonPath 和 pick 函数来确定是否需要根据当前域运行规则。我正在做的事情的简化版本在这里: global { dataset shopscotchMerch
我正在尝试在 Nifi 中使用 EvaluateJsonPath 处理器,但在使用 jayway jsonpath 语法时遇到了问题。我的对象如下所示: {"text":"my stuff", "ta
我有一个实现问题... #!/usr/bin/python #This is the API for BTC price request. # Average all the amounts, and
我正在使用放心框架,并且在它内部,它有 JsonPath 类。JsonPath 的方法签名为 getList(String path, Class T); 我尝试做这样的事情: List myList
我有这个“内容”响应,我需要从中断言一些值。 WebTestClient.BodyContentSpec content = response.expectStatus().isOk()
我正在读取一个文件,其中 Json 数据可用。我需要创建一个方法,它需要 jsonobject、jsonpath、type我需要检查 jsonpath 的数据类型,输入...如果数据类型相同,则应返回
我在使用 Stefan Goessner 的 JsonPath 查找数组或列表大小时遇到问题。我使用的是 json-path-2.0.0 版本。 我的 jsonpath 表达式是 $.orders
由于与我正在从事的项目相关的原因,我希望将对 JSON 文件的整个查询保存为一个字符串,例如,$.store.book[*].title(而不是必须将文档的每个级别临时存储为单独的对象)。 我目前正在
我正在尝试使用 Spring Boot Test 为 rest 端点编写单元测试,但是当我尝试使用 jsonPath 对 json 响应中的对象进行断言时,即使在以下情况下也会抛出 Assertion
我安装了 jsonpath-rw 1.4.0 sudo apt-get install python-jsonpath-rw 它带有一个 /usr/bin/jsonpath。但这在使用过滤器表达式时给
我有AWS步骤机,并且其中一个步骤用于使用SNS服务通知失败。我想从input json中选择一些元数据到传出消息中。所以我试图用jsonpath连接常量字符串,如下所示 "Notify Failur
我有如下的json字符串 [ { "topic": "inputTopic", "key": "0", "message": "test",
有没有办法通过过滤以下 json 中的“d”来提取“a”值? [ { "a":1, "b":{ "c":11,"d":12 } }, { "a":2, "b
我发现理解如何编写一个 jsonpath 来告诉我该字段中是否存在某些值有点困难。 例如:考虑这个 json: { "firstName": "John", "lastName" : "doe
我有一种情况,我有一个 json 字符串,它有一个子元素作为只包含字符串的数组。有没有办法获取包含特定字符串的数组的对象引用。 例子: { "Books":{ "History":[
我是一名优秀的程序员,十分优秀!