javax.json: Add new JsonNumber to existing JsonObject

后端 未结 3 1145
渐次进展
渐次进展 2020-12-31 02:59

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

JsonObject jo = ..         


        
3条回答
  •  余生分开走
    2020-12-31 03:35

    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 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();
    

提交回复
热议问题