Azrael Spare
Azrael Spare

Reputation: 33

How to modify an existing jsonobject in Java

I have an existing jsonobject from the javax.json.JsonObject class.

I can't for the life of me figure out how I can modify the existing values in it. Ideally I'd like to do something like this:

if(object.getString("ObjectUUID").length()==0){
    object.put("ObjectUUID", UUID.randomUUID().toString());
}

According to the API you aren't allowed to modify that map.

http://docs.oracle.com/javaee/7/api/javax/json/JsonObject.html

This map object provides read-only access to the JSON object data, and attempts to modify the map, whether direct or via its collection views, result in an UnsupportedOperationException.

Currently I'm getting around the problem with a quick hack but there must be a better solution than this:

if(object.getString("ObjectUUID").length()==0){
    JsonObjectBuilder job = Json.createObjectBuilder();
    job.add("ObjectUUID", UUID.randomUUID().toString());
    for(String key : object.keySet()){
        if(!key.equals("ObjectUUID")){
            job.add(key, object.get(key));
        }
    }
    object = job.build();
}

So the question how do you modify an existing jsonobject?

Upvotes: 3

Views: 4498

Answers (3)

Ryan J. McDonough
Ryan J. McDonough

Reputation: 1725

Without knowing the structure of the JSON object, it's a bit difficult to provide an answer that addresses your specific problem. The JsonObject instance is immutable, so you can't update it like Jackson's ObjectNode. As you've probably found, the JsonObject.add() method is basically useless, and depending on the implementation, may yield an UnsupportedOperationException. It's puzzling why it exists in the first place.

The way to modify the object is to create a JsonObjectBuilder instance that wraps the original JsonObject. If the object instance was your original JsonObject you'd probably want to do something like this:

if(object.getString("ObjectUUID").length()==0){
    object job = Json.createObjectBuilder(object)
                     .add("ObjectUUID", UUID.randomUUID().toString())
                     .build();
}

This took me a while to understand myself, and it gets a but more verbose if you have nested objects, etc.. If you're updating or replacing an object or array, you don't need to explicitly remove it before adding. There's pros and cons of the approach, but it beats the monthly ceremony of updating Jackson on a monthly basis :)

Upvotes: 3

Amit Portnoy
Amit Portnoy

Reputation: 6346

I think there is no other way to modify a javax.json.JsonObject.

You should consider using jackson-databind.

Upvotes: 1

hurricane
hurricane

Reputation: 6734

GSON Guide;

obj.addProperty("Id", "001");

System.out.println("Before: " + obj.get("Id")); // 001

obj.addProperty("Id", "002");

System.out.println("After: " + obj.get("Id")); // 002

Upvotes: 0

Related Questions