javax.json: Add new JsonNumber to existing JsonObject

后端 未结 3 1133
渐次进展
渐次进展 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<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();
    
    0 讨论(0)
  • 2020-12-31 03:41

    Try using JsonPatch

    String json ="{\"name\":\"John\"}";
    JsonObject jo = Json.createReader(new StringReader(json)).readObject();
    JsonPatch path = Json.createPatchBuilder()
            .add("/last","Doe")
            .build();
    jo = path.apply(jo);
    System.out.println(jo);
    
    0 讨论(0)
  • JsonObject is immutable but can be copied into a JsonObjecBuilder using lambdas.

    JsonObject source = ...
    JsonObjectBuilder target = Json.createObjectBuilder();
    source.forEach(target::add); // copy source into target
    target.add("name", "value"); // add or update values
    JsonObject destination = target.build(); // build destination
    
    0 讨论(0)
提交回复
热议问题