如何获取Json对象并将其存储在Hashmap中

时间:2020-03-07 18:13:43

标签: java servlets

在我的dopost中,我试图从请求中获取Json对象,然后使用fromJson根据该请求创建Profile对象,然后将其存储在我的哈希图中。当我尝试在代码中执行此操作并打印出哈希图时,我刚刚创建的新配置文件仅打印出{id = 0},但我硬编码的所有其他配置文件都可以打印出来。我的新个人资料未打印出用户名的姓氏年龄等。

有人知道我在做什么错吗?

我要作为json发送的内容

{
"4": {
    "id": "9",
    "username": "gfgf",
    "lastname": "hgfh",
    "favTeam": "Manc city",
    "age": "51"
}
}

我的代码

public class ProfileServlet extends HttpServlet 
{
protected HashMap<Integer, Profile> team = new HashMap<Integer, Profile>();

private static final long serialVersionUID = 1L;
private Gson gson = new Gson();

public ProfileServlet() 
{

    Profile profile1 = new Profile(1,"bob","bee","Manc city","21");
    Profile profile2 = new Profile(2,"billy","smith","Dortmud","25");
    Profile profile3 = new Profile(3,"john","jamesd","Aston Villa","44");

    int id = 1;
    int id2 = 2;
    int id3 = 3;

    team.put(id,profile1);
    team.put(id2,profile2); 
    team.put(id3,profile3);
}

public void sendAsJson(HttpServletResponse response, Object obj) throws IOException
{
    PrintWriter out = response.getWriter(); 
    response.setContentType("application/json; charset=UTF-8");

    String jsonString = gson.toJson(obj);


    out.print(jsonString);
    out.flush();

}

 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
 {
    response.setContentType("application/json; charset=UTF-8"); 
    int counter = 0;
    boolean breakloop = false;
    PrintWriter out = response.getWriter();

    String path = request.getPathInfo();



    if(path == null || path.equals("/"))
    {
        StringBuilder buffer = new StringBuilder();
        BufferedReader reader = request.getReader();

        String line;
        while ((line = reader.readLine()) != null)
        {
            buffer.append(line);
        }

        String myprofile = buffer.toString();
        Profile newp = gson.fromJson(myprofile, Profile.class);

        //loop to create my IDs in order
        while(breakloop == false)
        {
            if(!team.containsKey(counter))
            {
                newp.id = counter;
                breakloop = true;
            }
            else
                counter++;          

        }       

        team.put(newp.id,newp);
        sendAsJson(response,team);

    }
    else
    {
        response.sendError(400, "Incorrect request, make sure you typed the body correctly!");
    }



}

}

1 个答案:

答案 0 :(得分:0)

我解决了我的问题,我的代码没有任何问题,但是问题出在我的json请求中。这对我有用。

我的Json的工作原理,我想以某种方式添加那些外括号并没有得到我的完整要求

{
  "id": "9",
  "username": "gfgf",
  "lastname": "hgfh",
  "favTeam": "Manc city",
  "age": "51"
}