Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

gson - include class name when serializing java pojo -> json

Tags:

java

json

gson

Using GSON how do I append the class name of my List to my outputted json string? I've looked through the api and have missed any reference to do this. I'm using GsonBuilder in my real code but don't see any options for it either.

public class Person {
  String name;

  public Person(String name){
    this.name = name;
  }

  public static void main(String [] args){
    Person one = new Person("Alice");
    Person two = new Person("Bob");

    List<Person> people = new ArrayList<Person>();
    people.add(one);
    people.add(two); 

    String json = new Gson(people);
  }
}

This gives the following output:

json = [{"name": "Alice"},{"name": "Bob"}]

How do I achieve the following output? or something similar.

json = {"person":[{"name": "Alice"},{"name": "Bob"}]}

or

json = [{"person":{"name": "Alice"}},{"person":{"name": "Bob"}}]

Hope it's something trivial that I have just missed. Thanks in advance.

like image 786
feargal Avatar asked Nov 07 '12 15:11

feargal


1 Answers

I don't know if the answer is still interesting you but what you can do is the following:

public static void main(String [] args){
    Person one = new Person("Alice");
    Person two = new Person("Bob");

    List<Person> people = new ArrayList<Person>();
    people.add(one);
    people.add(two); 

    Gson gson = new Gson();
    JsonElement je = gson.toJsonTree(people);
    JsonObject jo = new JsonObject();
    jo.add("person", je);
    System.out.println(jo.toString()); //prints {"person":[{"name": "Alice"},{"name": "Bob"}]}
}
like image 190
Pierre Avatar answered Sep 29 '22 06:09

Pierre