В моем dopost я пытаюсь получить объект Json из запроса, а затем создать объект Profile из этого запроса, используя Json, и затем сохранить его в моем хэш-карте. Когда я пытаюсь сделать это в своем коде и распечатываю мою хэш-карту, тот новый профиль, который я только что создал, просто распечатывает {id = 0}, но все остальные профили, которые я жестко закодировал в печати, распечатываются нормально. Мой новый профиль не распечатывает мое имя, фамилию, возраст и т. Д. c.
Кто-нибудь знает, что я здесь не так делаю?
То, что я пытаюсь отправить как 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!");
}
}
}