Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
478 views
in Technique[技术] by (71.8m points)

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...