在递归解析JSON文件时,我有找到parentID和level值的问题。这是JSON文件和Java代码:
{
"user_quiz": [
{
"user_id": "55ce697e08b54122a0000214",
"user_score": "26"
},
{
"created": 1443115892,
"answers": [
{
"answer": "3",
"points": "4",
"complete": "true"
},
{
"answer": "30",
"points": "40",
"complete": "false"
}
]
},
{
"user_id": "55ce697e08b54122a0000214",
"quiz_id": "30061"
}
]
}
Java代码:
...
int id = 0, parentID = 0, level = 0;
ObjectMapper mapper = new ObjectMapper();
JsonParser parser = mapper.getJsonFactory().createJsonParser(new File("/Downloads/nnn.json"));
while (!parser.isClosed()) {
JsonToken token = parser.nextToken();
if (token == null) {
break;
}
while (parser.nextToken() != null) {
JsonNode node = mapper.readTree(parser);
if (node.isArray()) {
parseArray(node);
}
else if (node.isObject()) {
parseObject(node);
}
}
}
...
public static void parseArray(JsonNode node) throws JsonProcessingException, IOException {
if (node.isArray()) {
for (int i=0; i<node.size(); i++) {
JsonNode temp = node.get(i);
if (temp.isArray()) {
parseArray(temp);
}
else if (temp.isObject()) {
parseObject(temp);
}
}
}
}
...
public static void parseObject(JsonNode node) throws JsonProcessingException, IOException {
if (node.isObject()) {
Iterator<Map.Entry<String,JsonNode iterator=node.getFields();
while(iterator.hasNext()) {
Map.Entry<String,JsonNode jsonNode=iterator.next();
String key = jsonNode.getKey();
JsonNode temp = jsonNode.getValue();
System.out.println("level="+level);
System.out.println(tabs+"(id="+(++id)+",parentID="+parentID+")=="+key+"="+temp.toString());
if (temp.isArray()) {
parseArray(dtemp);
}
else if (temp.isObject()) {
parseObject(temp);
}
}
}
}
请帮我更改代码以获取parentID和级别值?
修改
所以我希望得到以下结果:
1.
key=user_quiz
val=user_quiz=[{"user_id":"55ce697e08b54122a0000214","user_score":"26"},{"created":1443115892,"answers":[{"answer":"3","points":"4","complete":"true"},{"answer":"30","points":"40","complete":"false"}]},{"user_id":"55ce697e08b54122a0000214","quiz_id":"30061"}]
id=1
parent_id=0
level=0
2.
key=user_id
val="55ce697e08b54122a0000214"
id=2
parent_id=1
level=1
3.
key=user_score
val="26"
id=3
parent_id=1
level=1
4.
key=created
val=1443115892
id=4
parent_id=1
level=1
5.
key=answers
val=[{"answer":"3","points":"4","complete":"true"},{"answer":"30","points":"40","complete":"false"}]
id=5
parent_id=1
level=1
6.
key=answer
val="3"
id=6
parent_id=5
level=2
7.
key=points
val="4"
id=7
parent_id=5
level=2
8.
key=complete
val="true"
id=8
parent_id=5
level=2
9.
key=answer
val="30"
id=9
parent_id=5
level=2
10.
key=points
val="40"
id=10
parent_id=5
level=2
11.
key=complete
val="false"
id=11
parent_id=5
level=2
12.
key=user_id
val="55ce697e08b54122a0000214"
id=12
parent_id=1
level=1
13.
key=quiz_id
val="30061"
id=13
parent_id=1
level=1
所以:
id = should increment on each new key
parent_id = is ID of parent key on which child belong
level = is level of depth, see on answers it's increased