How to add an attribute to javax.json.JsonObject

Although javax.json.JsonObject implements Map<String, JsonValue> -- it is immutable. Any modification attempt results in UnsupportedOperationException:


    @Test(expected = UnsupportedOperationException.class)
    public void immutable() {
        JsonObject dev = Json.createObjectBuilder().build();
        dev.put("dev", JsonValue.NULL);
    }

To add a new attribute to an existing JsonObject instance, you will have to copy it's attributes into a JsonObjectBuilder instance, add any attributes and eventually build a new instance:

package com.airhacks.jsonp;

import javax.json.Json;
import javax.json.JsonObject;
import javax.json.JsonObjectBuilder;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import org.junit.Test;

public class JsonTest {

    static final String STATUS_KEY = "status";

	
    @Test
    public void addAttributeToObject() {
        JsonObject dev = Json.createObjectBuilder().
                add("developer", "duke").
                build();
        String expected = "master";

        JsonObject devWithStatus = enrich(dev, STATUS_KEY, expected);
        assertThat(devWithStatus.getString(STATUS_KEY), is(expected));
        System.out.println(devWithStatus);
    }
	

    public JsonObject enrich(JsonObject source, String key, String value) {
        JsonObjectBuilder builder = Json.createObjectBuilder();
        builder.add(key, value);
        source.entrySet().
                forEach(e -> builder.add(e.getKey(), e.getValue()));
        return builder.build();
    }

}

See you at Java EE Workshops at Munich Airport, Terminal 2, particularly at: Effective Java EE 7! Is MUC too far? Checkout effectivejavaee.com

Comments:

And why cant the JsonObject create the builder for us, so we dont have to write error prone code like this?

Posted by Erlend Hamnaberg on August 11, 2016 at 10:57 AM CEST #

Nice!

I'm currently using the same code, and a version with a remove a property method:

public static JsonObject removeProperty(JsonObject origin, String key){
JsonObjectBuilder builder = Json.createObjectBuilder();

for (Map.Entry<String,JsonValue> entry : origin.entrySet()){
if (entry.getKey().equals(key)){
continue;
} else {
builder.add(entry.getKey(), entry.getValue());
}
}
return builder.build();
}

Posted by Anderson on April 06, 2018 at 06:03 PM CEST #

This is the code I have been looking for and this tool also helps me to analyse my big JSON data, https://jsonformatter.org

Posted by hex color on July 23, 2018 at 08:10 AM CEST #

I'm definitely not enjoying javax.json.JsonObject .. let's just say that it has an API that only a mother could love. If they wanted to replace org.json.JSONObject, they should have at least implemented half of its convenience functionality.

Posted by Bob on October 16, 2018 at 08:20 PM CEST #

Post a Comment:
  • HTML Syntax: NOT allowed
...the last 150 posts
...the last 10 comments
License