这是json文件
{ "session": { "name":"JSESSIONID", "value":"5864FD56A1F84D5B0233E641B5D63B52" }, "loginInfo": { "loginCount":77, "previousLoginTime":"2014-12-02T11:11:58.561+0530" } }
我想通过直接给XPath / JsonPath Like来更改name。的值
($.session.name).changevalue("MYSESSINID") 这只是一个例子
($.session.name).changevalue("MYSESSINID")
我正确使用杰克逊库,并使用以下代码通过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);
所以他们是一种通过XPath更改名称的方法
PropertyUtils.setProperty(jsonObj, "session.value", "new value");
仍然在文件中不起作用。
使用Jayways JsonPath,您可以:
private static final Configuration configuration = Configuration.builder() .jsonProvider(new JacksonJsonNodeJsonProvider()) .mappingProvider(new JacksonMappingProvider()) .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()); }
您可以配置默认的JsonProvider,因此不必在所有调用中都传递它。