一、源码编译
C++操作json字符串最好的库应该就是jsoncpp了,开源并且跨平台。它可以从这里下载。
下载后将其解压到任意目录,它默认提供VS2003和VS2010的工程文件,使用VS2010可以直接打开makefilesmsvc2010目录下的sln文件。
工程文件提供Jsoncpp的win32和win64静态库生成。点击生成--批生成选择需要生成的配置后即可生成jsoncpp静态库。生成的文件在makefilesmsvc2010(x64)Debug(Release)目录下。
二、测试工程
新建Win32控制台项目,为了区分Debug和Release版本,将Debug目录下的lib_json.lib改名为lib_json_d.lib,复制到新建的工程目录。
将jsoncpp目录下的include文件夹也复制到工程目录
修改工程属性如下
主文件代码如下:
// testJson.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
#include <fstream>
//添加需要的头文件
#include "include/json/json.h"
using namespace std;
//链接需要的库文件
#ifdef _DEBUG
#pragma comment(lib,"lib_json_d.lib")
#else
#pragma comment(lib,"lib_json.lib")
#endif
int _tmain(int argc, _TCHAR* argv[])
{
cout<<"测试json写入"<<endl;
Json::Value jsonRoot;
Json::Value jsonItem;
jsonItem["item1"] = "第一个条目";
jsonItem["item2"] = "第二个条目";
jsonItem["item3"] = 3;
jsonRoot.append(jsonItem);
jsonItem.clear();//清除上面已经赋值的项
jsonItem["First"]="1";
jsonItem["Second"]=2;
jsonItem["Third"]=3.0F;
jsonRoot.append(jsonItem);
cout<<jsonRoot.toStyledString()<<endl;
cout<<"测试json写入到文件"<<endl;
ofstream ofs;
ofs.open("test1.json");
ofs<<jsonRoot.toStyledString();
ofs.close();
cout<<"测试json读取"<<endl;
string sJson = jsonRoot.toStyledString();
jsonRoot.clear();
Json::Reader jsonReader;
if (!jsonReader.parse(sJson,jsonRoot))
{
return -1;
}
for (auto it = jsonRoot.begin();
it!=jsonRoot.end();
it++)
{
for (auto sit = it->begin();
sit != it->end();
sit++)
{
cout<<sit.key()<<"t"<<sit.name()<<endl;
}
}
cout<<"测试读取json文件"<<endl;
ifstream ifs;
ifs.open("test1.json");
jsonRoot.clear();
if (!jsonReader.parse(ifs, jsonRoot))
{
return -1;
}
ifs.close();
for (auto it = jsonRoot.begin();
it!=jsonRoot.end();
it++)
{
for (auto sit = it->begin();
sit != it->end();
sit++)
{
cout<<sit.key()<<"t"<<sit.name()<<endl;
}
}
return 0;
}
三、运行结果
四、相关下载
代码下载
原文链接: https://www.cnblogs.com/Reyzal/p/5494324.html
欢迎关注
微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍
原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/233425
非原创文章文中已经注明原地址,如有侵权,联系删除
关注公众号【高性能架构探索】,第一时间获取最新文章
转载文章受原作者版权保护。转载请注明原作者出处!