Correct way for parsing JSON objects containing arrays in Java Servlets (with Gson for example)

后端 未结 3 1718
别那么骄傲
别那么骄傲 2020-12-16 05:35

I know this is a topic much talked about, but I still wasn\'t able to find a correct and clear answer to my specific problem.

I\'ve got a JSON that looks like this:<

3条回答
  •  不知归路
    2020-12-16 05:45

    You aren't use JSON to send data to the server:

    data : myData,
    

    This specifies parameters as a JavaScript object, but not necessarily as JSON. What this means is that if you do a GET request with:

    data: {name1: "value1", name2: "value2"}
    

    The request will be:

    http://some/page?name1=value1&name2=value2
    

    This is basically what you're seeing with your first calls, where everything is being converted to a string, then sent as a form parameter.

    What you're doing in the second version is almost what you're supposed to do. The only difference is that you need to use a JavaScript object as the parameter to data, not just a string:

    data: {arbitraryNameHere: JSON.stringify(myData)}
    

    This will post your "myData" object as JSON, in the parameter named "arbitraryNameHere".

提交回复
热议问题