【发布时间】:2017-06-27 03:42:11
【问题描述】:
我看过很多 GSON 示例,但仍然无法适应我当前的结构。我似乎无法让它工作。它不断给我空指针异常错误。先谢谢了~
库存.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
}
【问题讨论】:
-
我当然希望你阅读this post
-
谢谢你的链接,我会看的~