#2928·gson

Singleton Constructors on JsonObjects

Author: SpeigerCreated Oct 31, 2025Updated Feb 2, 2026
Labelsenhancement

Problem solved by the feature

I frequently write Json Serializers & Parsers that have an object with a single element with them. Usually the Single element is also a JSONElement.

So if i want to create a JsonObject wrapper so i don't use primitives or Arrays as the base i have to do the following.

java
public JsonObject serialize(List<Object> myData) {
     JsonArray serializedData = new JsonArray();
     //Iterate over the list filling the array.
     JsonObject object = new JsonObject();
     object.add("myData", serializedData);
     return object;
}

I hope you see the problem? I know the Live writing option exist but sometimes i am not creating a JsonObject for writing into a stream.

Feature description

java
public JsonObject serialize(List<Object> myData) {
     JsonArray serializedData = new JsonArray();
     //Iterate over the list filling the array.
     return new JsonObject("myData", serializedData);
}

This should explain it itself.

Alternatives / workarounds

If this were C# i would use extensions :)