云起工作室 15711107967
15-boost-json
2022-10-09 17:14:47

常用json解析器

RapidJSON 是一个c++的小而全的json解析器及生成器。他的灵感来自RapidXml,他同时支持SAX 和DOM风格API

Jsoncpp 是个跨平台的开源库,主要包含三种类型 class:Value、Reader、Writer


cJSON 是个超轻巧,单文件,可以作为ANSI-C标准的JSON解析器


boost库里解析json

#include<boost/property_tree/ptree.hpp>

#include<boost/property_tree/json_parser.hpp>

using namespace boost::property_tree;


test.json 文件

{

“stu":{

"name":"小明",

"age":18,

}

"score":8.23,

"lesson":[

"math",

"english"

]

}


ptree pt

read_json("test.json",pt);


cout << pt.get<string>("stu.name") <<endl;

cout << pt.get<string>("stu.name.<xmlattr>.id") <<endl;

cout << pt.get<int>("stu.age") <<endl;

cout << pt.get<double>("stu.score") <<endl;

cout << pt.ge("stu.sex","保密") <<endl; 没有则设置默认值

auto child = pt.get_child("stu.lesson");

for(auto pos=child.begin();pos!=child.end();pos++){

cout << pos->first.data() << pos->second.data() <<endl;

}


解决中文乱码 ,先将test.json 保存为 utf-8编码格式

中文转换

#include<Window.h>

string st r= pt.get("stu.name");

int len = MultiByteToWideChar(CP_UTF8,NULL,str.data(),str.length(),0,0);

wchar_t * pw = new wchar_t[len+1];

MultiByteToWideChar(CP_UTF8,NULL,str.data(),str.length(),pw,len+1);

pw[len] =L "\0";

wcout.imbue(locale("",LC_CTYPE));

wcout <<L"姓名"<< pw << endl;