Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
461 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 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...