Posting a JSON array using Ajax and parsing in a servlet using Gson

I am new to Java and stick to this problem. I am creating an array in JavaScript that looks like this:

  var jsonObj = [];

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

    )

After that, I pass this to the servlet using Ajax:

 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 the servlet, in the doPostmethod, I wrote the code below

  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 class Wrapper

public class Wrapper {
  String Effect;
  String RuleID;
}

But this throws an exception below the line

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

What is wrong with parsing this JSON?

+4
source share
2 answers

Just the string you pass to the servlet is not valid JSON.

You are passing a Wrapper array, but in JSON the array is enclosed in a square bracket. Also, due to general erasure you need to use TypeToken.

, 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);

   }
}

:

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

, jQuery.ajax() API , jQuery.param(), 'application/x-www-form-urlencoded'

, . url.

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

rquest paramater, .

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

InputStream BufferedReader, ,

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

firebug Fire bug console

- , ajax-

data : JSON.stringify(jsonObj),

//

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

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 , json,

response.setContentType("application/json");

json

response.getWriter().write(jsonString);
+1

All Articles