c++的 nlohmann 读下面json的时候,输出:
Key:childrens
Processing Json body ... ....
010
北京
86
021
上海
86
022
天津
86
023
重庆
86
Key:id
value: 86
Key:name
value: 中国
Key:parentId
value:
其中,没有输出北京的下级内容, 中国输出到了最后面, 不知道啥原因, 还有,为什么这个json 开头和结尾是数组[]的形式? 我把这个去了,才可以正常解析:
json 内容:
[{
"id": "86",
"name": "中国",
"parentId": "",
"childrens": [
{
"id": "010",
"name": "北京",
"parentId": "86",
"childrens": [
{
"id": "0101",
"name": "朝阳区",
"parentId": "010",
"childrens": []
},
{
"id": "0102",
"name": "海淀区",
"parentId": "010",
"childrens": []
}
]
},
{
"id": "021",
"name": "上海",
"parentId": "86",
"childrens": []
},
{
"id": "022",
"name": "天津",
"parentId": "86",
"childrens": []
},
{
"id": "023",
"name": "重庆",
"parentId": "86",
"childrens": []
}
]
}]
c++ 代码:
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include "json.hpp"
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "ProtocolParser.h"
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using std::cin;
using std::cout;
using std::endl;
using std::string;
using nlohmann::json;
#define filename "data.json"
bool parsejsonbody(const json& subit);
int main(void)
{
ifstream file(filename, ios::in | ios::binary);
if(!file.is_open()){
throw runtime_error("Faile open the file.");
}
json j;
file >> j;
file.close();
if(j.is_object()){
for(auto& el:j.items()){
cout << "Key:" << el.key() << endl;
if(el.value().is_array() || el.value().is_object()){
cout << "Processing Json body ... ...." << endl;
parsejsonbody(el.value());
}else if (el.value().is_string()){
cout << "value: " << el.value().get<string>() << endl;
}
}
}
return 0;
}
bool parsejsonbody(const json& subit){
// for (auto &subit11 : subit.items()){
if (subit.is_array()){
for (const auto &subItem : subit){
for (auto &subit11 : subItem.items()){
if (subit11.value().is_string()){
string vstr = subit11.value().get<string>();
cout << vstr <<endl;
}}}}else if (subit.is_object()){
//else if(subit11alue().is_string()){
// cout << "subit11: " << *subit11 << endl;
for (auto &subit22 : subit.items()) {
if (subit22.value().is_string()){
string vstri = subit22.value().get<string>();
cout << "it key: " << subit22.key() << endl;
cout << "it value: " << vstri << endl;
} else if (subit22.value().is_array() || subit22.value().is_object()){
cout << "subit11 is array " << endl;
parsejsonbody(subit22.value());
}
}
}
return true;
}