Professor Chaos
Professor Chaos

Reputation: 9070

Gson attribute name for collection

I have this Entity

class Foo
{
   public String FooName;
   public String FooId;
}

I get an array of Foo from a method and I serialize it to json string like this

Foo[] foos = getFoos();
String json = gson.toJson(foos, Foo[].class);

This generates

[
    {
       "FooName" : "FirstFoo",
       "FooId" : "1"
    },
    {
       "FooName" : "SecondFoo",
       "FooId" : "2"
    }
]

which is fine except I have a requirement to have a wrapper attribute like this

{
  "foos":[
            {
               "FooName" : "FirstFoo",
               "FooId" : "1"
            },
            {
               "FooName" : "SecondFoo",
               "FooId" : "2"
            }
         ]
}

I know I can create a wrapper class

class Foos
{
    Foo[] foos;
}

and use Foos.class with gson but I have 100s of classes like Foo and I would hate to create a wrapper class for each. I was also thinking about just doing some string manipulation to the original json returned to add the wrapper attribut but I'm keeping that for plan B (or even C). So, I was wondering if there is a way in gson to add a wrapper attribute like what I'm asking above.

Thanks.

Upvotes: 1

Views: 287

Answers (2)

Andrew Mao
Andrew Mao

Reputation: 36920

JsonObject obj = new JsonObject();          
obj.add("foos", gson.toJsonTree(foos, Foo[].class));            
String json = obj.toString();

Upvotes: 1

Perception
Perception

Reputation: 80623

Heres a manual way to do this:

final Gson gson = new Gson();
final Foo[] foos = new Foo[] {};

final JsonElement elem = gson.toJsonTree(foos);
final JsonObject jsonObj = new JsonObject();
jsonObj.add("foo", elem);
System.out.println(jsonObj.toString());

Upvotes: 2

Related Questions