2

我使用 Gson 从List<Users>. 我想生成一个带有标题/正文结构的 JSON 文档,例如:

{
  "count" : 15,
  "users" : [
    {
      "userId" : 149,
      "userName" : "jack0231",
      "displayName" : "Jackie"
    },
    {
      "userId" : 301,
      "userName" : "helms_mighty",
      "displayName" : "Hippoman"
    }
...
  ]
}

目前我只是像这样自己写出结构:

StringBuilder jsonResp = new StringBuilder();
jsonResp.append("{\"count\":"+users.size()+",");
jsonResp.append("\"users\":");
Gson gs = new Gson();
jsonResp.append(gs.toJson(users));
jsonResp.append("}");

有没有更好的/内置的方法来做到这一点?谢谢!

4

2 回答 2

3

这就是你需要的。如果将列表放在另一个(简单)类中,则可以一步正确序列化,避免使用 StringBuilder 的所有样板。您可以直接运行此示例。

package stackoverflow.questions.q19966529;

import java.util.*;

import com.google.gson.Gson;

public class Q19966529 {

    public static class User{
        Long userId;
        String userName;
        String displayName;

        public User(Long userId, String userName, String displayName){
            this.userId = userId;
            this.userName = userName;
            this.displayName = displayName;             
        }
    }

    public static class UserList{
        private List<User> list = new ArrayList<>(); //java 7 
        private int count = 0;

        public void addUser(User u){
            list.add(u);
            count = list.size();

        }
    }

    public static void main(String[] args) {

        UserList ul = new UserList();
        ul.addUser(new User(149L, "jack0231", "Jackie"));
        ul.addUser(new User(301L, "helms_mighty", "Hippoman"));

        String json = new Gson().toJson(ul);
        System.out.println(json);
    }

}

这是结果:

{"list":[{"userId":149,"userName":"jack0231","displayName":"Jackie"},{"userId":301,"userName":"helms_mighty","displayName":"Hippoman"}],"count":2}

要看到它像您的示例一样格式化,您需要一个像这样的外部格式化程序

于 2013-11-14T00:07:55.110 回答
0

如何创建一个SerializedUsers类,为计数数据添加一个字段,为用户列表添加一个字段。比序列化这个类。

于 2013-11-13T23:49:07.407 回答