如何在 Java 中使用 XPath/JsonPath 更改 json 文件中的值 [英] How to change values in a json file using XPath/JsonPath in java

查看:40
本文介绍了如何在 Java 中使用 XPath/JsonPath 更改 json 文件中的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里是json文件

{
    "session":
        {
            "name":"JSESSIONID",
            "value":"5864FD56A1F84D5B0233E641B5D63B52"
        },
    "loginInfo":
        {
            "loginCount":77,
            "previousLoginTime":"2014-12-02T11:11:58.561+0530"
        }
}

我想改变name.by直接给XPath/JsonPath Like的值

I want to change the value of name.by directly giving XPath/JsonPath Like

($.session.name).changevalue("MYSESSINID")这只是一个例子

我正确使用 jackson 库并使用以下代码通过 XPath 读取

I am correctly using jackson library and using the below code for reading via 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 更改名称的方法

so is their a way to change the name by XPath

PropertyUtils.setProperty(jsonObj, "session.value", "new value");

仍然在文件中它不起作用.

still in the file its not working.

推荐答案

使用 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 = "{
"
        + ""session":
"
        + "    {
"
        + "        "name":"JSESSIONID",
"
        + "        "value":"5864FD56A1F84D5B0233E641B5D63B52"
"
        + "    },
"
        + ""loginInfo":
"
        + "    {
"
        + "        "loginCount":77,
"
        + "        "previousLoginTime":"2014-12-02T11:11:58.561+0530"
"
        + "    }
"
        + "}";

    JsonNode updatedJson = JsonPath.using(configuration).parse(originalJson).set("$.session.name", "MYSESSINID").json();

    System.out.println(updatedJson.toString());
}

您可以配置默认的 JsonProvider,这样您就不必在所有调用中都传递它.

You can configure the default JsonProvider so you don't have to pass it in all calls.

这篇关于如何在 Java 中使用 XPath/JsonPath 更改 json 文件中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆