how to use "set" with a predicate in JsonPath library

Viewed 47

JsonPath v.2.7.0

Using this code does not print expecting string

String jsonActual = "[" +
        "{\"count\":15,\"_id\":{\"DB User Name\":\"admin\",\"Session Activity Type\":\"LOGOFF\"}}," +
        "{\"count\":15,\"_id\":{\"DB User Name\":\"admin\",\"Session Activity Type\":\"LOGON\"}}" +
        "]";
Predicate predicate = new Predicate() {
    @Override
    public boolean apply(PredicateContext ctx) {
        String value = ctx.item(Map.class).get("DB User Name").toString();
        return value.equals("dbuser");
    }
};
String updatedActual = JsonPath.parse(jsonActual).set("$..['DB User Name']", "updated-Admin", predicate).jsonString();
System.out.println(updatedActual);

I would like to update 'DB User Name' field value globally with a condition - only when its value equal to "dbuser".

Actual output is:

[{"count":15,"_id":{"DB User Name":"updated-Admin","Session Activity Type":"LOGOFF"}},{"count":15,"_id":{"DB User Name":"updated-Admin","Session Activity Type":"LOGON"}}]

Expected output: the json-string should not be updated since the specified predicate does not match its criteria.

1 Answers

Do you accept to use another library?

https://github.com/octomix/josson

Josson josson = Josson.fromJsonString("[" +
    "{\"count\":15,\"_id\":{\"DB User Name\":\"admin\",\"Session Activity Type\":\"LOGOFF\"}}," +
    "{\"count\":16,\"_id\":{\"DB User Name\":\"dbuser\",\"Session Activity Type\":\"LOGON\"}}," +
    "{\"count\":17,\"_id\":{\"DB User Name\":\"dbuser\",\"Session Activity Type\":\"LOGOFF\"}}," +
    "{\"count\":18,\"_id\":{\"DB User Name\":\"admin\",\"Session Activity Type\":\"LOGON\"}}" +
    "]");

System.out.println(josson.getNode(
    "field(_id.field(DB User Name.if(equals('dbuser'),'updated-Admin',?)))")
    .toPrettyString());

Output

[ {
  "count" : 15,
  "_id" : {
    "DB User Name" : "admin",
    "Session Activity Type" : "LOGOFF"
  }
}, {
  "count" : 16,
  "_id" : {
    "DB User Name" : "updated-Admin",
    "Session Activity Type" : "LOGON"
  }
}, {
  "count" : 17,
  "_id" : {
    "DB User Name" : "updated-Admin",
    "Session Activity Type" : "LOGOFF"
  }
}, {
  "count" : 18,
  "_id" : {
    "DB User Name" : "admin",
    "Session Activity Type" : "LOGON"
  }
} ]
Related