How to use replace(K,V) in javax.json.JsonObject?

665 Views Asked by At

I need to read a JsonObject, modify a value, then go on. Let's say:

{ "aKey": "old value", , "anotherKey": "another value" }

should be changed to:

{ "aKey": "new value", "anotherKey": "another value" }

I read that JsonObject is immutable, it's in documentation and here: How to Modify a javax.json.JsonObject Object?

anyway JsonObject also provides a method called replace(K key, V value), with description: Replaces the entry for the specified key only if it is currently mapped to some value.

How to use this method? Any example?

I tried different way,s for example if I do like this:

jsonObject.replace("aKey", Json.createObjectBuilder().add("aKey", "new value").build());

I get java.lang.UnsupportedOperationException

I suppose I should do the replacement during a copy (??). That is, adding all the values of the old object except the value I want to replace?

1

There are 1 best solutions below

2
fresko On

Finally I created my own function. It returns the object with replaced key/value (in my case, String/String):

JsonObject myReplace(JsonObject jsonObject, String key, String newValue) {
    JsonObjectBuilder createObjectBuilder = Json.createObjectBuilder();
    Iterator it = jsonObject.entrySet().iterator();
    while (it.hasNext()) {
        JsonObject.Entry mapEntry = (JsonObject.Entry)it.next();
        if(mapEntry.getKey() == key){
            createObjectBuilder.add(key, newValue);
        }
        else{
            createObjectBuilder.add(mapEntry.getKey().toString(), mapEntry.getValue().toString());
        }
    }
    return createObjectBuilder.build();
}

So I can do:

myJsonObject = myReplace(myJsonObject, "aKey", "newValue"); // I know,  the assignement could be done in the method, too.