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