How to read json sent by ajax in servlet

前端 未结 3 1490
栀梦
栀梦 2020-12-02 23:11

I\'m new to java and I struggling with this problem for 2 days and finally decided to ask here.

I am trying to read data sent by jQuery so i can use it in my servlet

相关标签:
3条回答
  • 2020-12-02 23:37

    You won't be able to parse it on the server unless you send it properly:

    $.ajax({
        type: 'get', // it's easier to read GET request parameters
        url: 'masterpaket',
        dataType: 'JSON',
        data: { 
          loadProds: 1,
          test: JSON.stringify(test) // look here!
        },
        success: function(data) {
    
        },
        error: function(data) {
            alert('fail');
        }
    });
    

    You must use JSON.stringify to send your JavaScript object as JSON string.

    And then on the server:

    String json = request.getParameter("test");
    

    You can parse the json string by hand, or using any library (I would recommend gson).

    0 讨论(0)
  • 2020-12-02 23:47

    You will have to use the JSON parser to parse the data into the Servlet

    import org.json.simple.JSONObject;
    
    
    // this parses the json
    JSONObject jObj = new JSONObject(request.getParameter("loadProds")); 
    Iterator it = jObj.keys(); //gets all the 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
    }
    

    You will need a json library (e.g Jackson) to parse the json

    0 讨论(0)
  • 2020-12-02 23:59

    Using the import org.json.JSONObject instead of import org.json.simple.JSONObject did the trick for me.

    See How to create Json object from String containing characters like ':' ,'[' and ']' in Java.

    0 讨论(0)
提交回复
热议问题