包括Gson的顶级元素

时间:2013-12-11 22:04:44

标签: java json gson

我有这样的POJO

public class Pojo {
    ...
    public static String toJson(ArrayList<Pojo> pojos) {
        Gson gson = new Gson();
        return gson.toJson(pojos);
    }
}

输出结果为:

[
  {  
    "arrival": "19:12:30",
    "typeOfDay": "regular",
    "stopCode": "CMPZ",
    "route": "B",
    "id": 1
  },
  {
    "arrival": "19:13:30",
    "typeOfDay": "regular",
    "stopCode": "AVSV",
    "route": "B",
    "id": 2
  }
]

但我想要的是:

{
  "pojos": [
   {  
     "arrival": "19:12:30",
     "typeOfDay": "regular",
     "stopCode": "CMPZ",
     "route": "B",
     "id": 1
   },
   {
     "arrival": "19:13:30",
     "typeOfDay": "regular",
     "stopCode": "AVSV",
     "route": "B",
     "id": 2
   }
  ]
}

我怎么做?我正在使用Gson 2.2.4

2 个答案:

答案 0 :(得分:1)

像这样改变你的方法:

 public static String toJson(List<Pojo> pojos) {
      Gson gson = new Gson();
      Map m = new TreeMap();
      m.put("pojos", pojos);
      return gson.toJson(m);
  }

BTW,请注意我更改了签名,更喜欢界面(List)而不是实现(ArrayList)到您的方法中。

答案 1 :(得分:-1)

我不知道Gson是什么,但我想这样的东西会起作用......

    return gson.toJson({pojos:pojos});