【发布时间】:2017-05-02 12:12:58
【问题描述】:
我正在尝试使用 json.simple 从这个 json 文件中获取内容:
"Main": {
"Part1":{
"Length": 2,
"Flags": 2,
"Sequence": 4
},
"Part2":{
"Length": 2,
"Type":2,
"Main_Dest":4,
"Main_Source":4,
"Sequence":4,
"Data": {
"1":12,
"2":24
},
"Blank": 8
}
}
基本上,我想达到第 2 部分中的“类型”值,并在途中添加所有值。最后的意思是我想要总和10(长度+标志+序列+长度)和值“类型”的数字2。我在这里的主要问题是我必须通用,所以我不能只按名称收集值,因为它们可能会更改或可以添加其他值。只有值“Type”才会被准确地调用。
到目前为止,我所做的是:
private static void parseJson() {
String path = "...config.json";
boolean count = false;
int sum = 0;
try {
FileReader reader = new FileReader(path);
JSONParser jsonParser = new JSONParser();
JSONObject jsonObject = (JSONObject) jsonParser.parse(reader);
jsonObject.entrySet();
JSONObject main = (JSONObject) jsonObject.get("Main");
for (Iterator iterator = main.keySet().iterator(); iterator.hasNext();){
String key = (String) iterator.next();
//this is where I'm stumped. Do I keep going into the JSONObject until I get to a value?
if (count){
sum += (int) sahara.get(key);
}
if (key.equals("Type")){
count = true;
}
}
System.out.println(skip);
} catch (Exception e) {
}
}
显然我真的不知道我在做什么。如何迭代json文件的最底层?
作为一个小问题,如果我可以出售我的软件,我应该使用哪些 Json 解析器库?换句话说,哪个不会导致许可问题?
【问题讨论】:
-
您的示例不是有效的 JSON。缺少两个花括号。