解析JSON数组给出错误 [英] parsing JSON array gives error

查看:246
本文介绍了解析JSON数组给出错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下Javascript对象:

I have the following Javascript object:

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

并像这样发送:

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

我的Java类:

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

在我的servlet中:

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) {
            .
            .
            .

给出错误:期望BEGIN_ARRAY但在第1行X列处为STRING ,其中列号X是 [以字符串化JSON出现。

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?

编辑:我认为这可能与 JSON.stringify()行为有关字符串的Javascript数组。

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

JSON.stringify(o)返回:

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


推荐答案

我认为您字符串化结果中的引号太多。

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"]
        };

调用 JSON.stringify(o)

的结果是这个

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

注意在方括号中没有引号。

notice there are no quotes around my square brackets.

这篇关于解析JSON数组给出错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆