8

I convert the JsonObject to String, then parsed them back.

public static JsonObject clone(JsonObject o) {
  if (o == null)
    return null;

  StringWriter buffer = new StringWriter();
  JsonWriter writer = Json.createWriter(buffer);
  writer.write(o);
  writer.close();

  return Json.createReader(new StringReader(buffer.toString())).readObject();
}

I look for more elegant method.

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
sca.
  • 365
  • 4
  • 14
  • If disregarding that these objects are immutable, your question is a general Java question, how to clone an object in Java. Doesn't really have anything to do with JSON. One of the answers, by the way, is serialize it and then deserialize it, which is pretty much what you did here. – selalerer Feb 15 '14 at 04:59

1 Answers1

7

There is no point cloning JsonObject. The javadoc states

JsonObject class represents an immutable JSON object value (an unordered collection of zero or more name/value pairs).

Emphasis mine. Just re-use the object. No one will be able to change it.

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
  • 1
    What should one use if they want to clone and add an extra element inside it? – Sridhar Sarnobat Aug 23 '15 at 23:14
  • 2
    @Sridhar-Sarnobat Good question. I can't find anything obvious. It seems like you have to build the new `JsonObject` from the properties of the old `JsonObject`. You have to go through the full process yourself. – Sotirios Delimanolis Aug 24 '15 at 05:46