如何使用 Java 和 Gson 从 Json 获取对象列表

我尝试从 Json 文件中读取并将其转换为 Java 对象,我有以下 Java 代码来读取 Json:


class Item {

    String name;

    int itemId;

    Date AddTime;

    String group;

}


Gson gson = new Gson();

gson.fromJson(jsonFile, new TypeToken<Map<String, ArrayList<Item>>>() {}.getType());

并且 Json 文件包含以下数据:


{

  "item1": [{

    "name": "test1",

    "itemId": "1",

    "AddTime": "2018-09-05T10:35:56.015Z",

    "group": "computer"

  }, {

    "name": "test2",

    "itemId": "2",

    "AddTime": "2018-09-05T10:35:56.016Z",

    "group": "computer"

  }, {

    "name": "test3",

    "itemId": "3",

    "AddTime": "2018-09-05T10:35:56.017Z",

    "group": "computer"

  }],

  "item2": [{

    "name": "test4",

    "itemId": "4",

    "AddTime": "2018-09-05T10:35:56.015Z",

    "group": "computer"

  }, {

    "name": "test5",

    "itemId": "5",

    "AddTime": "2018-09-05T10:35:56.016Z",

    "group": "computer"

  }, {

    "name": "test6",

    "itemId": "6",

    "AddTime": "2018-09-05T10:35:56.017Z",

    "group": "computer"

  }]

}

我得到以下信息:


com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1

我是 Java 新手,有什么问题以及如何解决?


料青山看我应如是
浏览 150回答 1
1回答

慕莱坞森

我不确定这是否是您需要的,但我认为解决方案可能是这样的。根据你的数据集。在您的每个项目中,您都有一个带有测试的 arrayList (test1, test2 ...),因此您将需要这样的东西:&nbsp; &nbsp; class Item {&nbsp; &nbsp; &nbsp; &nbsp;ArrayList<Test> tests;&nbsp; &nbsp; }&nbsp; &nbsp; class Test{&nbsp; &nbsp; &nbsp; &nbsp;String name;&nbsp; &nbsp; &nbsp; &nbsp;int itemId;&nbsp; &nbsp; &nbsp; &nbsp;Date AddTime;&nbsp; &nbsp; &nbsp; &nbsp;String group;&nbsp; &nbsp; }
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java