parsing JSON array gives error

一笑奈何 提交于 2019-12-25 05:15:19

问题


I have the following Javascript object:

var o = {
      "username":"username",
      "args": [
          "1", "2", "3"
      ]
};

And send it like:

xhr.send(JSON.stringify(o));

My java class:

public class Command implements Serializable {
    private String username;
    private String[] args;
    //getters, setters constructors etc.
}

And in my servlet:

@Override
public void doPost(HttpServletRequest request, HttpServletResponse response){
    Command c;

    try {
        c = gson.fromJson(request.getReader(), Command.class);
    } catch(Exception e) {
            .
            .
            .

Gives the error: Expected BEGIN_ARRAY but was STRING at line 1 column X, where column number X is where the "[ appears in stringified JSON.

From what I understand this should be a very simple and straightforward thing. What am I doing wrong?

EDIT: I think it may be related to JSON.stringify() behavior with Javascript arrays of strings.

JSON.stringify(o) returns:

"{"username":"username","args":"[\"1\", \"2\", \"3\"]"}"

回答1:


Normal JavaScript arrays are designed to hold data with numeric indexes. Try using Object instead of an array.

Try using the below code for constructing the object and check the output :

var o = {};           // Object
o['username'] = 'username';
o['args'] = [];          // Array
o['args'].push('1');
o['args'].push('2');
o['args'].push('3');
var json = JSON.stringify(o);
alert(json);



回答2:


I think you have one too many quotes in your stringify result. When I construct the object like this:

 var o = {
            username: "username",
            args: ["1","2","3"]
        };

the result from calling JSON.stringify(o)

is this

"{\"username\":\"username\",\"args\":[\"1\",\"2\",\"3\"]}"

notice there are no quotes around my square brackets.



来源:https://stackoverflow.com/questions/25423883/parsing-json-array-gives-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!