【发布时间】:2019-10-25 15:11:16
【问题描述】:
通过 ajax 从我的 UI 我得到一个 JSON 数据,我试图将其插入到我的数据库中,我不知道我该怎么做,我知道如何使用 prepared statements 在数据库中插入一些东西但是在 JSON 的情况下,我完全糊涂了
这是我在 doPost 中得到的 JSON
{"ImageData":[{"Counter":"Counter A","Name":"CountA1.jpg","IsActive":"Y"},{"Counter":"Counter A","Name":"CountA2.jpg","IsActive":"Y"}]}
servlet 代码 -->
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Scanner scanner = new Scanner(request.getInputStream());
String imageData = scanner.nextLine();
System.out.println(imageData);
}
我需要解析这个 JSON,我该怎么做ps.setInt(index, 0);,我不知道
编辑/更新
作为 @Anjana Senanayake 回答我正在这样做
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Scanner scanner = new Scanner(request.getInputStream());
String imageData = scanner.nextLine();
System.out.println(imageData);
JSONObject jsonObj = new JSONObject(imageData);
JSONArray jsonArray = jsonObj.getJSONArray("ImageData");
JSONObject innerObj = new JSONObject(jsonArray); // this one is throwing error
// eror is `The type of the expression must be an array type but it resolved to JSONArray`
String counter = innerObj.getString("Counter");
String name = innerObj.getString("Name");
String isActive = innerObj.getString("IsActive");
System.out.println(counter);
}
但它在JSONObject innerObj = new JSONObject(jsonArray[0]); 处抛出错误,错误是The type of the expression must be an array type but it resolved to JSONArray
【问题讨论】:
-
这是一个相当广泛的问题,但如果您不限于 servlet,我建议您查看 Spring Boot 并使用 Jackson 注释将 JSON 映射到 java 对象,并在该对象上使用 JPA 注释进行映射它到数据库。