C++使用jsoncpp小结

理解和使用Jsoncpp进行Json操作
本文介绍了Jsoncpp的安装方法和基本使用,包括如何从字符串和文件解析Json,以及如何向文件写入Json数据。Jsoncpp是一个C++库,提供了Json数据的读写功能,适用于处理Json格式的数据。

一、Json语法:

Json语法是JavaScript语法的子集,Json中使用每条数据均为一个 键值对(key-value),书写格式为: "名称" : "值"

Json数据的值(value)类型可以是:
数字(整数或浮点数)、字符串(使用双引号""括起来)、逻辑值(true/false)、
数组(使用中括号[]表示数组)、对象(使用大括号{}表示对象)、null。

一个Json文件举例:

{
	"name": "zhangsan",
	"age": 70,
	"professional": {
		"english": 4,
		"putonghua": 2,
		"computer": 3,
	},
	"languages": [C++, C],
	"phone": {
		"number": "110",
		"type": "home",
	},
	"books": [{
			"name": "Linux kernel development",
			"price": 7.7,
		}, {
			"name": "Linux server development",
			"price": 8.0,
		}],
	"vip": true,
	"address": null
}


二、Jsoncpp使用:

2.1 Jsoncpp的安装方法:

//下载jsoncpp源码:
git clone https://githup.com/open-source-parsers/jsoncpp.git

cd jsoncpp-master
mkdir -p build/release
cd build/release

//使用cmake编译
cmake -DCMAKE_BUILD_TYPE=release -DBUILD_STATIC_LIBS=ON -DBUILD_SHARED_LIBS=OFF -DCMAKE_INSTALL_INCLUDEDIR=include/jsoncpp -DARCHIVE_INSTALL_DIR=. -G "Unix Makefiles" ../..

//编译和安装:
make
sudo make install
 
 //文件引用:
 #include <json/json.h>
 

2.2 jsoncpp的使用:

在使用jsoncpp时只需包含头文件 json.h 即可,jsoncpp中所有对象、类名都包含在 namespace Json{}; 内。

jsoncpp主要包含三种常用class类:

1class Value; 		//用于建立一个Json键值对2class Reader;  		//用于读取Json文件3class Writer;   	//用于写入Json文件

使用举例:

  1. 从字符串解析Json:
const char *str = "{\"uploadid\": \"UP000000\",\"code\": 100,\"msg\": \"\",\"files\": \"\"}";  

/*
{
	"uploadid": "UP000000",
	"code": 100,
	"msg": "\",
	"files": "\"
}
*/

Json::Reader reader;
Json::Value root;

if(reader.parse(str, root)) {	//reader将Json字符串解析到root,root将包含Json里所有子元素
	std::string upload_id = root["uploadid"].asString();	//访问结点:uploadid="UP000000"
	int code = root["code"].asInt();	
	//Json::Reader 提供访问Json文件的方法,asInt()表示按照Int型解析root["code"]这个节点的Value值
}

  1. 从文件解析Json:
int ReadJsonFromFile(const char* filename)  
{  
    Json::Reader reader;// 解析json用Json::Reader   
    Json::Value root; // Json::Value是一种很重要的类型,可以代表任意类型。如int, string, object, array         

    std::ifstream is;  
    is.open (filename, std::ios::binary );    
    if (reader.parse(is, root, FALSE))  
    {  
        std::string code;  
        if (!root["files"].isNull())  // 访问节点,Access an object value by name, create a null member if it does not exist.  
            code = root["uploadid"].asString();  
        
        code = root.get("uploadid", "null").asString();// 访问节点,Return the member named key if it exist, defaultValue otherwise.    

        int file_size = root["files"].size();  // 得到"files"的数组个数  
        for(int i = 0; i < file_size; ++i)  // 遍历数组  
        {  
            Json::Value val_image = root["files"][i]["images"];  
            int image_size = val_image.size();  
            for(int j = 0; j < image_size; ++j)  
            {  
                std::string type = val_image[j]["type"].asString();  
                std::string url  = val_image[j]["url"].asString(); 
                printf("type : %s, url : %s \n", type.c_str(), url.c_str());
            }  
        }  
    }  
    is.close();  

    return 0;  
}
  1. 向文件中插入Json:

void WriteJsonData(const char* filename)
{
    Json::Reader reader;  
    Json::Value root; // Json::Value是一种很重要的类型,可以代表任意类型。如int, string, object, array        

    std::ifstream is;  
    is.open (filename, std::ios::binary );    
    if (reader.parse(is, root))  
    {  
        Json::Value arrayObj;   // 构建对象  
        Json::Value new_item, new_item1;  
        new_item["date"] = "2011-11-11";  
        new_item1["time"] = "11:11:11";  
        arrayObj.append(new_item);  // 插入数组成员  
        arrayObj.append(new_item1); // 插入数组成员  
        int file_size = root["files"].size();  
        for(int i = 0; i < file_size; ++i)  
            root["files"][i]["exifs"] = arrayObj;   // 插入原json中 
        std::string out = root.toStyledString();  
        // 输出无格式json字符串  
        Json::FastWriter writer;  
        std::string strWrite = writer.write(root);
        std::ofstream ofs;
        ofs.open("test_write.json");
        ofs << strWrite;
        ofs.close();
    }  

    is.close();  
}

参考内容:
https://www.cnblogs.com/liaocheng/p/4243731.html

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值