I know this is a topic that has been talked about a lot, but I still could not find the right and clear answer to my specific problem.
I have a JSON that looks like this:
var myData = { "gameID" : gameID, "nrOfPlayers" : 2, "playerUIDs" : [123, 124] };
The question I have is exactly what is the right way (or better way, by style) to parse this in a Java servlet (e.g. using GSON)? First I send this JSON to the server using jQuery ajax, for example:
jQuery.ajax({ url : path, data : myData, success : successFunction, error : function(data) { console.log("Error: ", data); } , type : "post", timeout : 30000 });
Now in the servlet, I found out that I would have to parse this JSON as follows:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Gson gson = new Gson(); String gameID = gson.fromJson(request.getParameter("gameID"), String.class); String nrOfPlayers = gson.fromJson(request.getParameter("nrOfPlayers"), String.class); String[] playerUIDs = gson.fromJson(request.getParameter("playerUIDs"), String[].class); log.info(gameID); log.info(nrOfPlayers); log.info(playerUIDs[0] +" "+ playerUIDs[1]); }
But the playerUIDs IS NULL variable and, of course, PlayerUID [0] identifiers raise an exception!
Digging deeper, I found that when navigating through the request parameter names, it contained a parameter named "playerUIDs" [] " with a value of just 123 (the first int in the array). This was a strange reason why I didnโt seem to be able to access to the following values โโin general.
Then I read that JSON objects should be compressed before POST-IN, so I added JSON.stringify (myData), but now the request parameter names only contain one name that was a JSON object in string state:
INFO: Parameter name = {"gameID":"b6a51aabb8364b04bce676eafde1bc87","nrOfPlayers":2,"playerUIDs":[123,124]}
The only way I worked with was to create an inner class:
class GameStart { protected String gameID; protected int nrOfPlayers; protected int[] playerUIDs; }
And parsing JSON from the request parameter name, for example:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Gson gson = new Gson(); Enumeration en = request.getParameterNames(); GameStart start = null; while (en.hasMoreElements()) { start = gson.fromJson((String) en.nextElement(), GameStart.class); } log.info(start.gameID); log.info(String.valueOf(start.nrOfPlayers)); log.info(start.playerUIDs[0] +" "+ start.playerUIDs[1]); }
Now all the values โโare there, but it seems like a hack (reading JSON from the name of the request parameter) than an elegant solution, so I thought I would ask you guys what exactly would be the โrightโ way to do this? Am I missing something?
Thanks in advance!