google / google/gson

Singleton Constructors on JsonObjects

Open
#2,928 5 comments 0 reactions 0 assignees View on GitHub
enhancement
Dominant language
Java
Stars
24.2k
Forks
4.5k
Avg merge
6d 4h
Merged PRs (30d)
12

Description

# 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 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 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 :)

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.