Java 从字符串中获取 JSONObject
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3414092/
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
Getting JSONObject from String
提问by Anil Bharadia
How can I get a JSONObject
from a HttpServletRequest
in servlets?
如何JSONObject
从HttpServletRequest
servlet 中的a中获取 a ?
采纳答案by Erich Kitzmueller
Very simple:
很简单:
JSONObject o = new JSONObject(request.getParameter("WHATEVER"));
Edit: Since you use json-lib, it's
编辑:由于您使用 json-lib,它是
JSONObject o = (JSONObject) JSONSerializer.toJSON(request.getParameter("WHATEVER"));
for you.
为你。
回答by GobiasKoffi
GSON is a fairly good Java-based JSON library.
GSON 是一个相当不错的基于 Java 的 JSON 库。
回答by Vivin Paliath
See JSONObject(java.lang.String
). This will create a JSONObject
object if you're passing in a String that is valid JSON. The constructor throws a JSONException
so you will have to handle that. This is just as well if you are sending in invalid JSON.
见JSONObject(java.lang.String
)。JSONObject
如果您传入一个有效的 JSON 字符串,这将创建一个对象。构造函数抛出 aJSONException
所以你必须处理它。如果您以无效的 JSON 发送,这也同样适用。
It really depends on what you are doing. For the most part, JSONObject will use bean getters to create your JSON object (if you pass a bean to the constructor). Otherwise you can pass an object along with a String array of names. Here, JSONObject
will use reflection to figure out the public members of the object. It will then use the names you provide as the keys to this object.
这真的取决于你在做什么。在大多数情况下,JSONObject 将使用 bean getter 来创建您的 JSON 对象(如果您将 bean 传递给构造函数)。否则,您可以将对象与名称的 String 数组一起传递。在这里,JSONObject
将使用反射来找出对象的公共成员。然后它将使用您提供的名称作为该对象的键。
JSONObject
will handle anything of type Map
without a problem. But if your object is a List
, you need to use JSONArray
. Another problem is if your Map
contains a List
. Then, for some reason, JSONObject
can't figure out that it is a List
and will use the standard String representation of the List
(not what you want). The only way to handle that is to iterate over the Map
and built the JSONObject
manually.
JSONObject
可以Map
毫无问题地处理任何类型的事情。但是,如果您的对象是List
,则需要使用JSONArray
. 另一个问题是,如果您Map
包含List
. 然后,由于某种原因,JSONObject
无法确定它是一个List
并且将使用List
(不是你想要的)的标准字符串表示。处理这个问题的唯一方法是迭代Map
并JSONObject
手动构建。
As far as your question goes, I'm assuming that you have a servlet which has an action that will return JSON. In that case, make a new JSONObject
and use the PrintWriter
to and jsonObject.toString()
to output your JSON.
就您的问题而言,我假设您有一个 servlet,它有一个将返回 JSON 的操作。在这种情况下,创建一个新的JSONObject
并使用PrintWriter
to 和jsonObject.toString()
to 输出您的 JSON。
回答by BalusC
You're doing it a bit the hard way. There's certainly an easier way to do this. Just send as normal request parameters, not as JSON. You can use jQuery.serialize()
to gather all form fields as parameters. Here's a kickoff example of how the JSP should look like:
你这样做有点困难。当然有更简单的方法来做到这一点。只需作为普通请求参数发送,而不是 JSON。您可以使用jQuery.serialize()
收集所有表单字段作为参数。下面是 JSP 应该是什么样子的启动示例:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Test</title>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$(document).ready(function() {
$('#form').submit(function() {
$form = $(this);
$.post($form.attr('action'), $form.serialize(), function(response) {
alert(response); // "OK"
});
return false;
});
});
</script>
</head>
<body>
<form id="form" action="register" method="post">
<input type="text" name="username">
<input type="password" name="password">
<input type="submit">
</form>
</body>
</html>
And here is how the servlet which listens on an url-pattern
of /register/*
can look like:
这是侦听url-pattern
of的 servlet的/register/*
样子:
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String username = request.getParameter("username");
String password = request.getParameter("password");
System.out.println(username + "," + password);
response.getWriter().write("OK"); // You can write JSON string here.
}
With the jQuery formplugin it'll be more transparent.
使用jQuery 表单插件,它会更加透明。
$(document).ready(function() {
$('#form').ajaxForm(function(response) {
alert(response); // "OK"
});
});
To respond back from servlet to jQuery, it's easier if you return real JSON data. For example:
要从 servlet 响应 jQuery,如果返回真实的 JSON 数据会更容易。例如:
Map<String, Object> data = new HashMap<String, Object>();
if (userDAO.exist(username)) {
data.put("success", false);
data.put("message", "Username in use, please choose another");
} else {
userDAO.create(username, password);
data.put("success", true);
data.put("message", "User successfully registered");
}
response.setContentType("application/json");
response.getWriter().write(new Gson().toJson(data)); // Gson = Google Gson.
and then in jQuery:
然后在 jQuery 中:
$(document).ready(function() {
$('#form').ajaxForm(function(data) {
$('#message').addClass(data.success ? 'success' : 'error').text(data.message).show();
});
});
回答by cyber-monk
It seems like you must be using the net.sf.json.JSONObject
version of JSONObject (this is not the json.org version).
看来您必须使用net.sf.json.JSONObject
JSONObject的版本(这不是 json.org 版本)。
For the net.sf.json.JSONObject
version simply use
对于net.sf.json.JSONObject
版本只需使用
JSONObject.fromObject(Object obj)
where obj
is either
其中,obj
要么是
- a valid JSON formatted string
- a Bean POJO with getters and setters.
- 一个有效的 JSON 格式的字符串
- 带有 getter 和 setter 的 Bean POJO。