简体   繁体   English

如何使用GSON命名JSON对象数组?

[英]How to put name an array of JSON objects using GSON?

I'm creating a JSON file with GSON, but the arrays doesn't have names. 我正在使用GSON创建JSON文件,但是数组没有名称。

My result: 我的结果:

[
      {
      "name": Jonh,
      "date": "Feb 16, 2066",
      "hour": "10:15:00 PM"
   },
      {
      "name": Maria,
      "date": "Feb 16, 2066",
      "hour": "10:15:00 PM"
   }
]

What I need: 我需要的:

{
  "users": {
    "user": [
      {
        "name": John,
        "date": "Feb 16, 2066",
        "hour": "10:15:00 PM"
      },
      {
        "name": Maria,
        "date": "Feb 16, 2066",
        "hour": "10:15:00 PM"
      }
    ]
  }
}

Someone knows how can I put name an arrays? 有人知道如何命名数组吗?

--EDIT - 编辑

I'm using this code for generate my JSON file. 我正在使用此代码生成我的JSON文件。

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    @Path("user/list")
    public String getListUsers() throws Exception {

        List<Object> list;

        UserDAOImpl daoUser = new UserDAOImpl();
        list = daoUser.listAllUsers();

        Gson g = new Gson();
        return g.toJson(list);

    }

What you need is a new Object inside which you'll have to put your list and convert that object to JSON. 您需要的是一个新对象,您必须在其中放入列表并将该对象转换为JSON。

Gson gson = new GsonBuilder().create();
JsonArray jsonArray = gson.toJsonTree(list).getAsJsonArray();
JsonObject userJsonObject = new JsonObject();
jsonObject.add("user", jsonArray);
JsonObject usersJsonObject = new JsonObject();
jsonObject.add("users", usersJsonObject);

I haven't tried the code. 我没有尝试过代码。 I hope you get the idea. 希望您能明白。

Try this. 尝试这个。

Map<String, List<Object>> user = new TreeMap<>();
user.put("user", list);
Map<String, Map<String, List<Object>>> users = new TreeMap<>();
users.put("users", user);
Gson gson = new Gson();
return gson.toJson(users);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM