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

后端 未结 3 1274
失恋的感觉
失恋的感觉 2020-12-08 22:03

here is the json file

{
    \"session\":
        {
            \"name\":\"JSESSIONID\",
            \"value\":\"5864FD56A1F84D5B0233E641B5D63B52\"
        }         


        
相关标签:
3条回答
  • 2020-12-08 22:41
    PropertyUtils.setProperty(jsonObj, "session.value", "new value");
            PropertyUtils.setProperty(jsonObj, "session.name", "new name");
            mapper.writeValue(Json File ,jsonObj);
    
    0 讨论(0)
  • 2020-12-08 22:54

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

    JsonPath.parse(Body).set(fieldPath, Value);
    
    0 讨论(0)
  • 2020-12-08 22:56

    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.

    0 讨论(0)
提交回复
热议问题