客户端通过 HTTP PUT 向我发送 JSON 文件,文件如下:
{
"nomPers": "Testworking",
"prenomPers": "WorkingTest",
"loginPers": "Work",
"pwdPers": "Ing",
"active": true
},
我使用 HTTPServlet 作为 WebService 框架和 org.json 库来处理 Json。我也在使用 Tomcat 服务器。由于 Tomcat 无法为此 HTTP 动词创建参数映射,因此我必须使用 JSON 对象。
所以我做了一些搜索和尝试,但仍然无法使其工作,这是我的代码:
@Override
public void doPut(HttpServletRequest request, HttpServletResponse response) {
// this parses the incoming json to a json object.
JSONObject jObj = new JSONObject(request.getParameter("jsondata"));
Iterator<String> it = jObj.keys();
while(it.hasNext())
{
String key = it.next(); // get key
Object o = jObj.get(key); // get value
System.out.println(key + " : " + o); // print the key and value
}
因此,我将传入的 Json 解析为要使用的 Json 对象,然后创建一个 Iterator 以便能够遍历该对象并获取和打印每个键/值对的数据。
问题是我收到 NullPointerException 错误。
我猜是因为 request.getParameter("jsondata")。看来我没有得到任何参数。我想我必须从通过请求获得的数据创建一个字符串来提供 JSONObject 构造函数,但我不知道如何实现这一点。