2

I'm creating a JSON file with GSON, but the arrays doesn't have names.

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.

    @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);

    }
4
  • what is your input and relevant source code? Commented Jun 4, 2017 at 3:40
  • This is a json array. What clase are those ojects? You need a wrapping class that contamina the list to generarte it as want it. Commented Jun 4, 2017 at 4:01
  • Objects are from User class Commented Jun 4, 2017 at 4:05
  • You already seem to know how to create a JSON object ({}) using a Java class, and a JSON array ([]) using a List, so what's the difficulty in creating more Java objects to create more JSON objects? I don't see the problem. Commented Jun 4, 2017 at 4:10

2 Answers 2

2

What you need is a new Object inside which you'll have to put your list and convert that object to 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.

Sign up to request clarification or add additional context in comments.

Comments

0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.