gson - include class name when serializing java po

2020-02-07 02:16发布

问题:

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.

回答1:

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"}]}
}


标签: java json gson