The proper way to parse JSON objects containing arrays in Java Servlets (e.g. using Gson)

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!

+6
source share
3 answers

You do not use JSON to send data to the server:

 data : myData, 

Specifies parameters as a JavaScript object, but not necessarily as JSON. This means that if you execute a GET request with:

 data: {name1: "value1", name2: "value2"} 

The request will be:

 http://some/page?name1=value1&name2=value2 

This is basically what you see with your first calls, where everything is converted to a string and then sent as a form parameter.

What you do in the second version is almost what you should do. The only difference is that you need to use the JavaScript object as the data parameter, not just the string:

 data: {arbitraryNameHere: JSON.stringify(myData)} 

This will place your myData object as JSON in a parameter named "arbitrary name".

+8
source

In the real world, you usually do not send the real json object to the servlet, and you will not often process fill values โ€‹โ€‹from the request in most cases. JSON is a JavaScript object designation - and is great for use in client-side coding.

It's easier to use a query string for parameters, rather than a post with json (which apparently you are actually doing). host / url GameID = 5 &? nrPlayers = 2

Regarding how to populate values, conditional configuration is the way to go for clean code. You can use frameworks such as spacers to offload the entire transfer of values โ€‹โ€‹to the framework. Not sure what your whole application looks like, your intention to write (that is, writing servlets from scratch is a great way to learn, but not spread practice in real application development environments), so this may or may not be a useful answer.

+1
source

JSON for the server using jQuery ajax method

 function send() { var myData = {"gameID": 30, "nrOfPlayers": 2, "playerUIDs": [123, 124] }; jQuery.ajax({ url: "servletName", data: JSON.stringify(myData), success: function(){ //console.log(JSON.stringify(myData)); }, error: function(data) { console.log("Error: ", data); }, type: "post", timeout: 30000 }); } 

Sender button

 <button onclick="send();" id="send">Send</button> 

Java Servlet Processing

 public class servletName extends HttpServlet { class GameStart { protected String gameID; protected int nrOfPlayers; protected int[] playerUIDs; } 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); } System.out.println(start.gameID); System.out.println(start.playerUIDs[0] +" "+ start.playerUIDs[1]); } } 
+1
source

Source: https://habr.com/ru/post/911445/


All Articles