c++:json 库 jsoncpp & CJsonObject

文章目录前言jsoncpp 库示例代码1. 解析 json 对象2. 解析带有数组的 json注意CJsonObject 库示例代码前言jsoncpp 库linkjsoncpp是一个可以与JSON 进行交互的C++库示例代码1. 解析 json 对象#include <iostream>#include <string>#include <jsoncpp/json/json.h> using namespace std; int main()
摘要由CSDN通过智能技术生成

前言

jsoncpp 库

link

  • jsoncpp是一个可以与JSON 进行交互的C++

示例代码

link

1. 解析 json 对象

#include <iostream>
#include <string>
#include <jsoncpp/json/json.h>
 
using namespace std;
 
int main()
{
   
	// 待解析的 json 字符串
    string strJsonContent = "{\"role_id\": 1,\"occupation\": \"paladin\",\"camp\": \"alliance\"}";
    
    // 待解析的结果
    int nRoleDd = 0;
    string strOccupation = "";
    string strCamp = "";
    
    // json 解析器
    Json::Reader reader;
    // json 根对象
    Json::Value root;
 
 	// 将 strJsonContent 解析到 root
    if (reader.parse(strJsonContent, root))
    {
   
        nRoleDd = root["role_id"].asInt();
        strOccupation = root["occupation"].asString();
        strCamp = root["camp"].asString();
    }
 
    cout << "role_id is: " << nRoleDd << endl;
    cout << "occupation is: " << strOccupation << endl;
    cout << "camp is: " << strCamp << endl;
 
    return 0;
}

编译:g++ jsonstrparse.cpp -o jsonstrparse -ljsoncpp

2. 解析带有数组的 json

#include <iostream>
#include <string>
#include <jsoncpp/json/json.h>
 
using namespace std;
/*
{
	"list" : [
		{
			"camp" : "alliance",
			"occupation" : "paladin",
			"role_id" : 1
		},
        {
        	"camp" : "alliance",
        	"occupation" : "Mage",
			"role_id" : 2
		}
	],
	"type" : "roles_msg",
	"valid" : true
}

*/
int main()
{
   
	// 待解析的 json 字符串
    string strJsonContent = "{\"list\" : [{ \"camp\" : \"alliance\",\"occupation\" : \"paladin\",\"role_id\" : 1}, \
        {\"camp\" : \"alliance\",\"occupation\" : \"Mage\",\"role_id\" : 2}],\"type\" : \"roles_msg\",\"valid\" : true}";

	// 待解析的结果
    string strType;
    int nRoleDd = 0;
    string strOccupation;
    string strCamp;
    
    // 对象
    Json::Reader reader;
    Json::Value root;
 
 	// 解析
    if (reader.parse(strJsonContent, root))
    {
   
        // 【获取非数组内容】
        strType = root["type"].asString();
        cout << "type is: " << strType << endl;
 
        // 【获取数组内容】
        if (root["list"].isArray())
        {
   
        	// 数组内有几个对象(size)
            int nArraySize = root["list"].size();
            for (int i = 0; i < nArraySize; i++)
            {
   
                nRoleDd = root[
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值