简体   繁体   English

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

[英]How to get the list of objects from Json using Java and Gson

I try to read from a Json file and convet it to Java object, I have the following Java code to read the 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());

And the Json file contains the following data: 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"
  }]
}

I got the following: 我得到以下内容:

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

I am new to Java, what is the problem and how to fix it? 我是Java新手,有什么问题以及如何解决?

I'm not sure if this is what you need, but I think the solution could be something like this. 我不确定这是否是您需要的,但是我认为解决方案可能是这样的。

According with your dataset. 根据您的数据集。 Inside of each one of your items you have an arrayList with tests (test1, test2...) so you will need something like this: 在每个项目的内部,都有一个带有测试的arrayList(test1,test2 ...),因此您将需要以下内容:

    class Item {
       ArrayList<Test> tests;
    }

    class Test{
       String name;
       int itemId;
       Date AddTime;
       String group;
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM