这是json文件
{
"session":
{
"name":"JSESSIONID",
"value":"5864FD56A1F84D5B0233E641B5D63B52"
},
"loginInfo":
{
"loginCount":77,
"previousLoginTime":"2014-12-02T11:11:58.561+0530"
}
}
我想改变name.by的值直接给XPath/JsonPath喜欢
($.session.name). changvalue("MYSESSINID")
这只是一个例子
我正确使用jackson库并使用以下代码通过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,这样您就不必在所有调用中传递它。
PropertyUtils.setProperty(jsonObj, "session.value", "new value");
PropertyUtils.setProperty(jsonObj, "session.name", "new name");
mapper.writeValue(Json File ,jsonObj);
我发现在Json中交换的最简单方法(当我的身体是JSONObject时)
import com.jayway.jsonpath.JsonPath;
JsonPath.parse(Body).set(fieldPath, Value);