简体   繁体   中英

How to change values in a json file using XPath/JsonPath in java

here is the json file

{
    "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

($.session.name).changevalue("MYSESSINID") this is just a Example

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);

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.

Using Jayways JsonPath you can:

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());
}

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

PropertyUtils.setProperty(jsonObj, "session.value", "new value");
        PropertyUtils.setProperty(jsonObj, "session.name", "new name");
        mapper.writeValue(Json File ,jsonObj);

the easiest way i found to exchange inside Json (When my Body is a JSONObject )

import com.jayway.jsonpath.JsonPath;


JsonPath.parse(Body).set(fieldPath, Value);

I tried Kalle's way, it always said jsonPath not found when I am adding a new field.

So I used this updated way to add a new field

        @Test
        public void a_node_can_be_updated_and_created() throws ParseException{
        
        System.out.println(originalJson);
        JSONObject json = (JSONObject)new JSONParser(JSONParser.DEFAULT_PERMISSIVE_MODE).parse(originalJson);
        JSONObject session = JsonPath.read(json, "$.session");
        session.appendField("new__field", "new__value");        // add a new field
        session.put("name", "Justin2");                         // update an existing field
        System.out.println(JsonFormatter.prettyPrint(json.toJSONString()) );
        
    }

This new way also doesn't need Jackson library, only Jayway.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM