如何在 Java 中使用 XPath/JsonPath 更改 json 文件中的值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27244431/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to change values in a json file using XPath/JsonPath in java
提问by vaibhavcool20
here is the json file
这是json文件
{
"session":
{
"name":"JSESSIONID",
"value":"5864FD56A1F84D5B0233E641B5D63B52"
},
"loginInfo":
{
"loginCount":77,
"previousLoginTime":"2014-12-02T11:11:58.561+0530"
}
}
I want to change the value of name.by directly giving XPath/JsonPath Like
我想改变 name.by 的值直接给 XPath/JsonPath Like
($.session.name).changevalue("MYSESSINID")
this is just a Example
($.session.name).changevalue("MYSESSINID")
这只是一个例子
I am correctly using Hymanson library and using the below code for reading via XPath
我正确使用 Hymanson 库并使用以下代码通过 XPath 阅读
ObjectMapper mapper = new ObjectMapper();
Object jsonObj=mapper.readValue(new File(Json file), Object.class);
Object name=PropertyUtils.getProperty(jsonObj, "session.name");
System.out.println("Name:"+name);
so is their a way to change the name by XPath
他们通过 XPath 更改名称的方法也是如此
PropertyUtils.setProperty(jsonObj, "session.value", "new value");
still in the file its not working.
仍然在文件中它不起作用。
回答by kalle
Using Jayways JsonPathyou can:
使用Jayways JsonPath,您可以:
private static final Configuration configuration = Configuration.builder()
.jsonProvider(new HymansonJsonNodeJsonProvider())
.mappingProvider(new HymansonMappingProvider())
.build();
@Test
public void a_value_can_be_updated(){
String originalJson = "{\n"
+ "\"session\":\n"
+ " {\n"
+ " \"name\":\"JSESSIONID\",\n"
+ " \"value\":\"5864FD56A1F84D5B0233E641B5D63B52\"\n"
+ " },\n"
+ "\"loginInfo\":\n"
+ " {\n"
+ " \"loginCount\":77,\n"
+ " \"previousLoginTime\":\"2014-12-02T11:11:58.561+0530\"\n"
+ " }\n"
+ "}";
JsonNode updatedJson = JsonPath.using(configuration).parse(originalJson).set("$.session.name", "MYSESSINID").json();
System.out.println(updatedJson.toString());
}
You can configure the default JsonProvider so you don't have to pass it in all calls.
您可以配置默认的 JsonProvider,这样您就不必在所有调用中都传递它。
回答by vaibhavcool20
PropertyUtils.setProperty(jsonObj, "session.value", "new value");
PropertyUtils.setProperty(jsonObj, "session.name", "new name");
mapper.writeValue(Json File ,jsonObj);