为什么不能使用Jayway JsonPath设置json属性的值?

问题描述 投票:0回答:3

我有一个需要在JSON中更新值的要求。我需要更新的密钥的路径也基于某种条件,因此我必须在属性文件中维护路径。这是我的JSON

String jsonString = "{\"delivery_codes\": [{\"postal_code\": {\"district\": \"District1\", \"pin\": 201001, \"pre_paid\": \"Y\", \"cash\": \"Y\", \"pickup\": \"Y\", \"repl\": \"N\", \"cod\": \"Y\", \"is_oda\": \"N\", \"sort_code\": \"GB\", \"state_code\": \"UP\"}}]}";

现在我的要求是,假设我需要将pre_paid的值更新为N,但需要动态地对pre_paid的路径进行动态处理,因为有时我可能需要更新state_code或sort_code或pre_paid等。所以我用了JSONPath:

String jsonPathExpressionForDistrict = "$['delivery_codes'][0]['postal_code']['district']";
String jsonPathExpressionForState_code = "$['delivery_codes'][0]['postal_code']['state_code']";

这些路径我需要存储在某些属性文件/数据库中。

我可以通过以下代码读取属性:

JsonPath.parse(jsonString).read(jsonPathExpressionForDistrict , JsonNode.class) -> This gives me value 'District1'

但是当我尝试使用以下代码更新值时:

JsonPath.parse(jsonString).put(jsonPathExpressionForDistrict , "District2", String.class);

这给了我下面的错误:

线程“ main”中的异常com.jayway.jsonpath.InvalidModificationException:只能添加地图的属性在com.jayway.jsonpath.internal.PathRef $ ObjectPropertyPathRef.put(PathRef.java:265)在com.jayway.jsonpath.JsonPath.put(JsonPath.java:304)在com.jayway.jsonpath.internal.JsonContext.put(JsonContext.java:221)在com.jayway.jsonpath.internal.JsonContext.put(JsonContext.java:199)在com..service.ServiceImpl.main(ServiceImpl.java:179)

有人请为此指导我。

java json jsonpath
3个回答
1
投票

当需要更新已经存在的节点的值时,应使用set方法。希望以下内容对您有所帮助:

String jsonString = "{\"delivery_codes\": [{\"postal_code\": {\"district\": \"District1\", \"pin\": 201001, \"pre_paid\": \"Y\", \"cash\": \"Y\", \"pickup\": \"Y\", \"repl\": \"N\", \"cod\": \"Y\", \"is_oda\": \"N\", \"sort_code\": \"GB\", \"state_code\": \"UP\"}}]}";

    String jsonPathExpressionForDistrict = "$['delivery_codes'][0]['postal_code']['district']";
    String jsonPathExpressionForState_code = "$['delivery_codes'][0]['postal_code']['state_code']";

    DocumentContext documentContext = JsonPath.parse(jsonString);
    System.out.println(documentContext.jsonString());

    String read = documentContext.read(jsonPathExpressionForDistrict);

    System.out.println(read);
    documentContext.set(jsonPathExpressionForState_code, "District2");

    System.out.println(documentContext.jsonString());

1
投票

我知道已经晚了,但是也许可以帮助其他人。OP收到该错误,因为值jsonPathExpressionForDistrict是属性的路径,而不是JSON对象或映射。

要将district2添加到postal_code,路径应为"$['delivery_codes'][0]['postal_code']"

要使用JSonPath更新/添加JSON中的任何值,我们可以使用本文中提到的方法,但是需要检查并使该路径在源JSON对象中有效。


0
投票

使用org.json库。

Org.JSON

您可以使用JSONArray并获取数组中Items的键。

您可以获得这样的物品:

array.getJSONObject(i).getInt("postal_code");

在这种情况下,我是JSONArray中的项目。

祝你好运。

© www.soinside.com 2019 - 2024. All rights reserved.