Json的解析和生成

json:
{
	"shemename":"方案""eventname":"事件""name":"lucy"
	"lucy":
	{
		"age":17,
		"gender":"female"
	}
	"course":
	[
		"math",
		"chinese",
		"English"
	]
}
//读取
bool readJson()
{
	bool res;
    JSONCPP_STRING errs;
    Json::Value root;
    Json::CharReaderBuilder readerBuilder;
    std::unique_ptr<Json::CharReader> reader(readerBuilder.newCharReader());
    res = reader->parse(inputJson.c_str(), inputJson.c_str()+inputJson.length(), &root, &errs);
    //inputJson 是输入的json串
     if (!res || !errs.empty()) {
        std::cout << "js串解析异常 " << errs << std::endl;
        return false;
    }
    std::cout<<root["shemename"].asString()<<std::endl;
    std::cout<<root["eventname"].asString()<<std::endl;
    std::cout<<root["name"].asString()<<std::endl;//可以直接读取

//注意嵌套json读取的方法 
    Json::Value lucy=root["lucy"];
    std::cout<<lucy["age"].asInt()<<std::endl;
    std::cout<<lucy["gender"].asString()<<std::endl;

//注意列表数组的读取方法
 	Json::Value course=root["course"];
 	std::cout<<"course";
 	for(int i=0;i<course.size();++i)
 	{
 		std::cout<<course[i]<<std::endl;
	}

    return true;
}
// 转换类型
Int asInt() const;
UInt asUInt() const;
Int64 asInt64() const;
UInt64 asUInt64() const;
LargestInt asLargestInt() const;
LargestUInt asLargestUInt() const;
float asFloat() const;
double asDouble() const;
bool asBool() const;
方法二:
	Json::CharReaderBuilder b;
	Json::CharReader* reader(b.newCharReader());
	Json::Reader reader;
	JSONCPP_STRING jsErStr;
	Json::Value root;
	std::string aaa, bbb, ccc;
	if (reader->parse(str_input.c_str(), str_input.c_str()+std::strlen(str_input.c_str()),&root, &jsErStr))
	{
		aaa = root["xxx"].asString();
		bbb = root["xxx"].asString();
		ccc = root["xxx"].asString();
	}
	delete reader;
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值