jsoncpp的使用demo

Jsoncpp下载地址:

编译生成后的库文件为:jsoncpp.lib

下面是一个使用的demo,copy过去自己看看就会了:

#include <iostream>
#include <fstream>
#include <ostream>
#include <assert.h>
#include <string>
#include "json\json.h"  //Jsoncpp的头文件

#pragma  comment(lib, "jsoncpp.lib")

int main()
{
	Json::Value jsonRoot; //定义根节点
	Json::Value jsonItem; //定义一个子对象

	Json::CharReaderBuilder builder;
	Json::CharReader* reader(builder.newCharReader());


	/*******************从Json字符串读取***********************/
	JSONCPP_STRING errs;
	const char* str = "{\n\t\"people1\" : \n\t{\n\t\t\"age\" : 20,\n\t\t\"name\" : \"ZhangSan\"\n\t},\n\t\"people2\" : \n\t{\n\t\t\"age\" : 19,\n\t\t\"name\" : \"LiSi\"\n\t}\n}\n";

	bool ok = reader->parse(str, str + std::strlen(str), &jsonRoot, &errs);
	std::string name = jsonRoot["people1"]["name"].asString();  //"ZhangSan"
	int age = jsonRoot["people2"]["age"].asInt();  //19
	size_t len = jsonRoot.size();// 2 //Json数组的长度
	jsonRoot.clear();//清除jsonRoot

	/*********************生成Json字符串*********************/
	jsonItem["name"] = "ZhangSan"; //添加数据1
	jsonItem["age"] = 20;
	//jsonRoot.append(jsonItem);  //添加匿名对象
	jsonRoot["people1"] = jsonItem;
	jsonItem.clear(); //清除jsonItem

	jsonItem["name"] = "LiSi"; //添加数据2
	jsonItem["age"] = 19;
	jsonRoot["people2"] = jsonItem;

	name = jsonRoot["people1"]["name"].asString();   //"ZhangSan"
	age = jsonRoot["people2"]["age"].asInt();   //19

	/***********************保存为字符串*********************/
	std::string outStr = jsonRoot.toStyledString();  //保存为字符串
	std::cout << outStr << std::endl; //输出字符串到控制台


	/**********************遍历Json数组对象******************/
	for (auto v : jsonRoot)
	{
		name = v["name"].asString();
		age = v["age"].asInt();
	}

	/***********************输出到文件*********************/
	std::ofstream ofs; //标准输出流
	ofs.open("sample.json"); //创建文件
	ofs << jsonRoot.toStyledString(); //输出
	ofs.close();


	/***********************从文件读取*********************/
	std::ifstream ifs; //标准输入流
	ifs.open("sample.json");
	assert(ifs.is_open());
	jsonRoot.clear();
	
	builder["collectComments"] = false;
	bool success = parseFromStream(builder, ifs, &jsonRoot, &errs); //从ifs中读取数据到jsonRoot
	
	len = jsonRoot.size();

	name = jsonRoot["people2"]["name"].asString();   //"Lisi"
	age = jsonRoot["people1"]["age"].asInt();   //20

	ifs.close();

	system("pause");

	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值