Java 使用 Ajax 发布 JSON 数组并使用 Gson 在 servlet 中解析

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20117432/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 23:15:50  来源:igfitidea点击:

Posting JSON array using Ajax and parse in servlet using Gson

javaajaxparsingservletsgson

提问by Ashes

I am new to Java and stuck with this problem. I'm building an array in JavaScript which looks like this

我是 Java 的新手,并且遇到了这个问题。我正在用 JavaScript 构建一个数组,它看起来像这样

  var jsonObj = [];

  jsonObj.push(
  {
     Effect: "Deny",
     RuleID: "Rule1"
   },
   {
     Effect: "Deny",
     RuleID: "Rule2"
   },
   {
     Effect: "Deny",
     RuleID: "Rule3"
    },....

    )

After this I am passing this to servlet using Ajax:

在此之后,我使用 Ajax 将其传递给 servlet:

 jQuery.ajax({ 
    url: "http://localhost:8080/PolicyConsumerServlet/PolicyServlet",  
    dataType: "json",
    type: 'POST',
    data: {jsondata : JSON.stringify(jsonObj)},

     contentType: 'application/json',
        mimeType: 'application/json',
        success: function(data) { 

            alert('Hi');
        },
    error: function(jqXHR, textStatus, errorThrown) {
        alert("error occurred");
    } 
});

In servlet, in doPostmethod I have written below code

在servlet中,doPost我在下面的代码中编写了方法

  StringBuffer jb = new StringBuffer();
  String line = null;

  BufferedReader reader = request.getReader();
  RequestMaker.requestProcess();
  while ((line = reader.readLine()) != null)
      jb.append(line);

  String jsonstring = jb.toString(); 
  Gson gson = new Gson();

  Wrapper[] data = gson.fromJson(jsonstring, Wrapper[].class);

  System.out.println(jb);

and Wrapper class is

和包装类是

public class Wrapper {
  String Effect;
  String RuleID;
}

But this is throwing exception at below line

但这在下面的行抛出异常

    Wrapper [] data = gson.fromJson(jsonstring, Wrapper[].class);

What is wrong in parsing this JSON?

解析这个 JSON 有什么问题?

采纳答案by giampaolo

Simply, the string you are passing to the servlet is not a valid JSON.

简单地说,您传递给 servlet 的字符串不是有效的 JSON。

You are passing an array of Wrapper, but in JSON an array is enclosed by square bracket. Moreover, due to generic erasure, you need to use a TypeToken.

您正在传递一个 Wrapper 数组,但在 JSON 中,一个数组用方括号括起来。此外,由于通用擦除,您需要使用TypeToken.

I provide you with an example that shows the correct JSON for you case and how to parse it. It won't be difficult for you to copy and paste relevant part into your code. You can paste and run directly my example in you IDE to see it working.

我为您提供了一个示例,该示例显示了适用于您的案例的正确 JSON 以及如何解析它。将相关部分复制并粘贴到代码中对您来说并不困难。您可以直接在 IDE 中粘贴并运行我的示例以查看它的工作情况。

package stackoverflow.questions;

import com.google.gson.*;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import stackoverflow.questions.q18123430.Q18123430.ObjectA;

public class Test {

   public static class Wrapper {

      String Effect;
      String RuleID;

      @Override
      public String toString() {
         return "Wrapper [Effect=" + Effect + ", RuleID=" + RuleID + "]";
      }

   }

   public static void main(String[] args) {

      String json = "[ { \"Effect\": \"Deny\",  \"RuleID\": \"Rule1\" }, { \"Effect\": \"Deny\",  \"RuleID\":  \"Rule2\"  }]";
      Type listType = new TypeToken<List<Wrapper>>() {}.getType();

      Gson g = new Gson();
      List<Wrapper> list = g.fromJson(json, listType);
      for (Wrapper w : list)
         System.out.println(w);

   }
}

and this is the console result:

这是控制台结果:

Wrapper [Effect=Deny, RuleID=Rule1]
Wrapper [Effect=Deny, RuleID=Rule2]

回答by Asif Bhutto

I believe jQuery.ajax() API states that the data have to be converted into a query string using jQuery.param() and also content type have to be 'application/x-www-form-urlencoded'

我相信 jQuery.ajax() API 声明必须使用 jQuery.param() 将数据转换为查询字符串,并且内容类型必须是“application/x-www-form-urlencoded”

The data argument data to be sent to the server. It is converted to a query string in this case data is parameter of query string of url.

要发送到服务器的数据参数数据。在这种情况下,它被转换为查询字符串 data 是 url 查询字符串的参数。

data =[
       {"Effect":"Deny","RuleID":"Rule1"},
       {"Effect":"Deny","RuleID":"Rule2"},{"Effect":"Deny","RuleID":"Rule3"}
      ]

In servlet you can get it from rquest paramater, not from reader.

在 servlet 中,您可以从 rquest 参数中获取它,而不是从阅读器中获取。

String jsonData =  req.getParameter("jsondata");

If you will get data from inputStream or BufferedReader then you will get data in servlet as like below

如果您将从 inputStream 或 BufferedReader 获取数据,那么您将在 servlet 中获取数据,如下所示

jsondata=%5B%7B%22Effect%22%3A%22Deny%22%2C%22RuleID%22%3A%22Rule1%22%7D%2C%7B%22Effect%22%3A%22Deny%22%2C%22RuleID%22%3A%22Rule2%22%7D%2C%7B%22Effect%22%3A%22Deny%22%2C%22RuleID%22%3A%22Rule3%22%7D%5D

Here is firebug screen snap shortFire bug console

这是萤火虫屏幕快照短火虫控制台

If you want to get data from reader object in servlet then you need to change ajax call optional data prameters as

如果要从 servlet 中的读取器对象获取数据,则需要将 ajax 调用可选数据参数更改为

data : JSON.stringify(jsonObj),

//Not this one

//不是这个

 data: {jsondata : JSON.stringify(jsonObj)},

Your ajax call is like this

你的ajax调用是这样的

jQuery.ajax({
          url: "http://localhost:8080/PolicyConsumerServlet/PolicyServlet",
          type : 'POST',
          dataType: "json",
          data : JSON.stringify(jsonObj),
           contentType : 'application/json',
           mimeType : 'application/json',
           success : function(data) {
                         alert('Hi');
                     },
                error : function(jqXHR, textStatus, errorThrown) {
                    alert("error occurred");
                }
            });

datatype argument specifies the type of the data coming from server as json you need to set content type in servlet

datatype 参数将来自服务器的数据类型指定为 json 您需要在 servlet 中设置内容类型

response.setContentType("application/json");

You can send json response on stream as

您可以在流上发送 json 响应作为

response.getWriter().write(jsonString);