使用GSON在Java中访问JSON格式

时间:2017-06-27 03:42:11

标签: java json string gson

我已经看过很多GSON示例,但仍然无法适应我当前的结构。我似乎无法使它工作。它一直给我空指针异常错误。提前谢谢〜

inventory.txt

{   
"inventory":
    {
        "id": 0,
        "name": "nameName",
        "image": "imageName",
        "color": "colorName",
        "subChain1": {
            "location": ["country1", "country2", "country3", "country4"],
            "role": ["role1", "role2"]
        },
        "subChain2": {
            "location": ["country1", "country2", "country3", "country4", "country5", "country6", "country7"],
            "role": ["role1", "role2", "role3", "role4", "role5"]
        },
        "subChain3": {
            "chain": ["chain1", "chain2", "chain3", "chain4", "chain5"],
            "location": ["country1", "country2", "country3", "country4", "country5", "country6", "country7"],
            "role": ["role1", "role2", "role3", "role4", "role5"]
        }
    }
}
以下

是我尝试过的:

mainClass.java

BufferedReader inventoryItems = new BufferedReader(new FileReader("./src/inventory.txt"));
Response response = gson.fromJson(moduleReader, Response.class);

String[] role_in_subChain1 = response.getInventory().getSubChain1().get("subChain1").getRole();

String[] role_in_subChain2 = response.getInventory().getSubChain2().get("subChain2").getRole();

List<String> chain_in_subChain3 = response.getInventory().getSubChain3().get("subChain3").getChain();

String name = response.getInventory().getName();

response.java

class Response {
Module inventory;
//getters and setters
}

class Module{
String id;
String name;
String image;
String color;
Map<String, chain1and2> subChain1;
Map<String, chain1and2> subChain2;
Map<String, speciality> subChain3;
//getters and setters
}

class chain1and2{
String[] role;
List<String> location;
//getters and setters
}

class speciality{
List<String> chain;
List<String> role;
List<String> location;
//getters and setters
}

1 个答案:

答案 0 :(得分:1)

您的子链接不是地图。它们只是嵌套对象。

class Module{
  String id;
  String name;
  String image;
  String color;
  Chain1and2 subChain1;
  Chain1and2 subChain2;
  Speciality subChain3;
  //getters and setters
}