Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javax.json: Add new JsonNumber to existing JsonObject

Tags:

java

json

I want to add properties to an existing instance of JsonObject. If this property is boolean, this is quite easy:

JsonObject jo = ....;
jo.put("booleanProperty", JsonValue.TRUE);

However, I also want to add a JsonNumber but I couldn't find a way to create an instance of JsonNumber. Here's what I could do:

JsonObjectBuilder job = Json.createObjectBuilder();
JsonNumber jn = job.add("number", 42).build().getJsonNumber("number");
jo.put("numberProperty", jn);

But I couldn't think of a more dirty way to accomplish my task. So - is there are more direct, cleaner approach to add a JsonNumber to an existing instance of JsonObject?

like image 337
aRestless Avatar asked Oct 13 '14 17:10

aRestless


2 Answers

Okay, I just figured it out myself: You can't.

JsonObject is supposed to be immutable. Even if JsonObject.put(key, value) exists, at runtime this will throw an UnsupportedOperationException. So if you want to add a key/value-pair to an existing JsonObject you'll need something like

private JsonObjectBuilder jsonObjectToBuilder(JsonObject jo) {
    JsonObjectBuilder job = Json.createObjectBuilder();

    for (Entry<String, JsonValue> entry : jo.entrySet()) {
        job.add(entry.getKey(), entry.getValue());
    }

    return job;
}

and then use it with

JsonObject jo = ...;
jo = jsonObjectToBuilder(jo).add("numberProperty", 42).build();
like image 109
aRestless Avatar answered Sep 28 '22 13:09

aRestless


Try using JsonPatch

String json ="{\"name\":\"John\"}";
JsonObject jo = Json.createReader(new StringReader(json)).readObject();
JsonPatch patch = Json.createPatchBuilder()
        .add("/last","Doe")
        .build();
jo = patch.apply(jo);
System.out.println(jo);
like image 24
mark786110 Avatar answered Sep 28 '22 14:09

mark786110