1

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?

fresko
  • 1,890
  • 2
  • 24
  • 25

1 Answers1

1

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.
fresko
  • 1,890
  • 2
  • 24
  • 25
  • 1
    This function will do the trick. Whoever is reading this, be aware though that if that ``JsonObject`` is itself a child of another object - or array - then modifying it will HAVE NO EFFECT whatsoever on its parent! As parent object (or array) is immutable, too. And their parent(s) are immutable as well. The whole tree of objects and arrays have to be swapped for modified ones. – leonidos79 Jun 16 '21 at 17:06
  • 1
    WOW! You helped me to solve the problem I've been struggling with for a whole day – Lilia Jun 05 '23 at 23:07