【问题标题】:Getting error not a JSON array when using gson使用 gson 时出现错误不是 JSON 数组
【发布时间】:2013-01-16 18:42:46
【问题描述】:

我的 json 字符串是:

{
    "sigTemplateId": 1,
    "name": "Test Ticket Template",
    "groups": "[{\"sigTemplateId\": 1, \"sigTemplateGroupId\": 1, \"name\": \"Group 1\", \"ordinal\": 1}]"
}

这从我的 jsp 发送到 servlet。 Servlet 代码是:

Gson gson = new Gson();

if (jsonData != null) {
    Type objType = new TypeToken<SigTemplateObj>() {}.getType();
    SigTemplateObj sigTemplateToSave = gson.fromJson(jsonData, objType);
    //SigTemplateObj sigTemplateToSave = gson.fromJson(jsonData, SigTemplateObj.class);
}

我得到:java.lang.IllegalStateException:这不是 JSON 数组。 gson 试图解析组数组:JsonDeserializer com.google.gson.DefaultTypeAdapters$CollectionTypeAdapter@1f4db697 无法反序列化 json 对象 "[{\"sigTemplateId\": 1, \"sigTemplateGroupId\": 1, \"name\" : \"Group 1\", \"ordinal\": 1}]" 给定类型 java.util.ArrayList

我的目标代码是:

public class SigTemplateObj {

    int sigTemplateId;
    String dyninkName;
    int dyninkFormId;
    String name;

    //children collections
    ArrayList<SigTemplateFieldObj> fields;
    ArrayList<SigTemplateGroupObj> groups;
...
}

public class SigTemplateGroupObj {
    int sigTemplateGroupId;
    int sigTemplateId;
    int ordinal;
    String name;
...
}

我已经尝试了上面的代码和这行代码,两次都得到了相同的结果。

SigTemplateObj sigTemplateToSave = gson.fromJson(jsonData, SigTemplateObj.class);

任何帮助将不胜感激。 谢谢, 埃里克

现在我只需要修复我的 javascript 以将组数组视为数组而不是字符串:

var testObject = new Object();
        testObject.sigTemplateId = 1;
        testObject.name = 'Test Ticket Template';
        testObject['groups'] = [];
        var testGroup = new Object();
        testGroup.sigTemplateId = 1;
        testGroup.sigTemplateGroupId = 1;
        testGroup.name = 'Group 1';
        testGroup.ordinal = 1;
        testObject.groups.push(testGroup);

        var json = JSON.stringify(testObject);

【问题讨论】:

  • 您的 JS 代码为我生成了有效的 JSON。我将它粘贴到 Chrome 的控制台,并获取了一个 console.log(json)。

标签: java javascript json gson


【解决方案1】:

groups数组不是数组,而是字符串:

"groups": "..."

试试这个 JSON:

{
    "sigTemplateId": 1,
    "name": "Test Ticket Template",
    "groups": [{"sigTemplateId": 1, "sigTemplateGroupId": 1, "name": "Group 1", "ordinal": 1}]
}

【讨论】:

  • 我更改了我的字符串并且它有效,但是我将如何更改我的 javascript 以便它不会将其视为字符串,而是将其视为数组?
  • Javascript: var testObject = new Object(); testObject.sigTemplateId = 1; testObject.name = '测试票模板'; testObject['groups'] = []; var testGroup = new Object(); testGroup.sigTemplateId = 1; testGroup.sigTemplateGroupId = 1; testGroup.name = '组 1'; testGroup.ordinal = 1; testObject.groups.push(testGroup); var json = JSON.stringify(testObject);
  • 请更新您的问题并在此处插入您的 JS 代码。并将 javascript 标签添加到您的问题中。
  • 我发现原型库和 JSON 库之间的兼容性问题已经回答了我的问题。修复方法是删除 Array.prototype.toJSON;
猜你喜欢
  • 1970-01-01
  • 2011-11-11
  • 1970-01-01
  • 1970-01-01
  • 2018-04-12
  • 1970-01-01
  • 1970-01-01
  • 2014-03-11
  • 1970-01-01
相关资源
最近更新 更多