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;
import static org.junit.Assert.assertThat;
import org.junit.Test;

public class JsonTest {

    static final String STATUS_KEY = "status";

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

        JsonObject devWithStatus = enrich(dev, STATUS_KEY, expected);
        assertThat(devWithStatus.getString(STATUS_KEY), is(expected));

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


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

NEW: Online Workhop Effective WebApps without Frameworks is also coming to: MUC Airport.

Airport MUC workshops: Web (SPA, PWAs, Offline, Desktop, Mobile) Applications Essentials and Effective Web Applications. No migrations. #usetheplatform

Podcast: and newsletter:

A book about rethinking Java EE Patterns


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 #


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)){
} else {
builder.add(entry.getKey(), entry.getValue());

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,

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

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