在 Java Servlet 中解析包含数组的 JSON 对象的正确方法(例如使用 Gson)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9829819/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Correct way for parsing JSON objects containing arrays in Java Servlets (with Gson for example)
提问by T?nis Pool
I know this is a topic much talked about, but I still wasn't able to find a correct and clear answer to my specific problem.
我知道这是一个经常被谈论的话题,但我仍然无法为我的具体问题找到正确和明确的答案。
I've got a JSON that looks like this:
我有一个看起来像这样的 JSON:
var myData = { "gameID" : gameID,
"nrOfPlayers" : 2,
"playerUIDs" : [123, 124]
};
The Question I have is exactly what is the correct way (or best way, style wise) to parse this in a Java servlet (using GSON for example)? First I send this JSON to the server using jQuery ajax method like this:
我的问题是在 Java servlet(例如使用 GSON)中解析它的正确方法(或最佳方式,风格明智)是什么?首先,我使用 jQuery ajax 方法将此 JSON 发送到服务器,如下所示:
jQuery.ajax({
url : path,
data : myData,
success : successFunction,
error : function(data) {
console.log("Error: ", data);
} ,
type : "post",
timeout : 30000
});
Now in the servlet I've learned that I should have been able to parse that JSON like this:
现在在 servlet 中,我了解到我应该能够像这样解析 JSON:
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 variable IS NULL and of course playerUIDs[0] throws an exception!
但是 playerUIDs 变量是 NULL,当然 playerUIDs[0] 会抛出异常!
Digging deeper I found that when looping over the request parameter names, it contained a parameter named "playerUIDs[]"with the value of only 123(the first int in the array). This was strange cause I didn't seem to be able to access the next values at all.
深入挖掘,我发现在循环请求参数名称时,它包含一个名为“playerUIDs[]”的参数,其值仅为 123(数组中的第一个 int)。这很奇怪,因为我似乎根本无法访问下一个值。
Then I read that JSON objects should be stringifyed before POST-ing so I added JSON.stringify(myData), but now the request parameter names only contained ONE namewhich was the JSON object itself in a stringified state:
然后我读到 JSON 对象应该在 POST 之前被字符串化,所以我添加了 JSON.stringify(myData),但现在请求参数名称只包含一个名称,它是处于字符串化状态的 JSON 对象本身:
INFO: Parameter name = {"gameID":"b6a51aabb8364b04bce676eafde1bc87","nrOfPlayers":2,"playerUIDs":[123,124]}
The only way I seemed to get this to work was by creating a inner class:
我似乎让它起作用的唯一方法是创建一个内部类:
class GameStart {
protected String gameID;
protected int nrOfPlayers;
protected int[] playerUIDs;
}
And parsing the JSON from the request parameter name, like this:
并从请求参数名称解析 JSON,如下所示:
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 values are there, but this seems more like a hack (reading JSON from request parameter name) than an elegant solution, so I thought I'd ask you guys what exactly would be the "correct" way of doing this? Am I missing something obvious?
现在所有的值都在那里,但这似乎更像是一个黑客(从请求参数名称读取 JSON)而不是一个优雅的解决方案,所以我想我会问你们到底什么是“正确”的方法?我错过了一些明显的东西吗?
Thanks in advance!
提前致谢!
采纳答案by Brendan Long
You aren't use JSON to send data to the server:
您不使用 JSON 将数据发送到服务器:
data : myData,
This specifies parameters as a JavaScript object, but not necessarily as JSON. What this means is that if you do a GET request with:
这将参数指定为 JavaScript 对象,但不一定是 JSON。这意味着如果您使用以下内容执行 GET 请求:
data: {name1: "value1", name2: "value2"}
The request will be:
请求将是:
http://some/page?name1=value1&name2=value2
This is basically what you're seeing with your first calls, where everything is being converted to a string, then sent as a form parameter.
这基本上就是您在第一次调用时所看到的,其中所有内容都被转换为字符串,然后作为表单参数发送。
What you're doing in the second version is almost what you're supposed to do. The only difference is that you need to use a JavaScript object as the parameter to data
, not just a string:
你在第二个版本中所做的几乎就是你应该做的。唯一的区别是你需要使用一个 JavaScript 对象作为 的参数data
,而不仅仅是一个字符串:
data: {arbitraryNameHere: JSON.stringify(myData)}
This will post your "myData" object as JSON, in the parameter named "arbitraryNameHere".
这会将您的“myData”对象作为 JSON 发布到名为“arbitraryNameHere”的参数中。
回答by JasonG
In the real world you typically wouldn't send an actual json object to a servlet and you won't often handle populating values from a request in most circumstances. JSON is JavaScript object notation - and it's great when consumed for use in client side coding.
在现实世界中,您通常不会将实际的 json 对象发送到 servlet,并且在大多数情况下您不会经常处理来自请求的填充值。JSON 是 JavaScript 对象表示法 - 用于客户端编码时非常有用。
It's easier to use query string for params rather than a post with json (which it appears you are actually doing). host/url?gameId=5&nrPlayers=2
使用 params 的查询字符串比使用 json 的帖子更容易(看起来您实际上正在这样做)。host/url?gameId=5&nrPlayers=2
As far as how to populate values, convention-over-configuration is the way to go for cleanest code. You can use a frameworks like struts to offload all of the transfer of values onto the framework. Not sure what your whole application looks, your intention for writing (ie writing servlets from scratch is a great way to learn but not common practice in real application development environments) like so this may or may not be a helpful answer.
至于如何填充值,约定优于配置是获得最干净代码的方法。您可以使用像 struts 这样的框架来将所有的值转移卸载到框架上。不确定你的整个应用程序是什么样子,你的写作意图(即从头开始编写 servlet 是一种很好的学习方式,但在实际应用程序开发环境中不是常见的做法),像这样这可能是也可能不是一个有用的答案。
回答by Daniel Sonkeng
JSON to the server using jQuery ajax method
JSON 到服务器使用 jQuery ajax 方法
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
Java servlet 处理
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]);
}
}