下载地址为:http://sourceforge.net/projects/jsoncpp。本文使用的 jsoncpp 版本为:0.5.0
1.将 jsoncpp-src-0.5.0\include 目录下的json文件夹拷贝至工程目录下
2.将 jsoncpp-src-0.5.0\src\lib_json 目录下的所有源文件全部拷贝至json目录下
3.在使用json的cpp文件引用 #include "json\json.h"
4.在 解决方案资源管理器 -> 源文件 -> 添加 -> 现有项 添加json目录下的3个cpp文件 “json_reader.cpp,json_value.cpp,json_writer.cpp”
在调试过程中会遇到一些错误,相应改之即可:
json_reader.cpp 中加入#include "stdafx.h",将#include<json/reader.h>改为#include“json/reader.h”,#include<json/value.h>改为#include "json/value.h";
json_value.cpp中加入#include "stdafx.h",将#include <json/value.h>改为#include "json/value.h", #include <json/writer.h>改为 #include "json/writer.h";
json_writer.cpp中加入#include "stdafx.h",将#include <json/writer.h>改为#include "json/writer.h"。
Json::Value 只能处理 ANSI 类型的字符串,不能处理Unicode 编码的, BOOL与bool有区别的
测试代码:
#include <iostream>
#include <string>
#include "json\json.h"
int main(void)
{
//解析Json的方法
Json::Value root;//表示一个json格式的对象
Json::Value arrayObj;
Json::Value item;
for(int i=0;i<10;i++)
{
item["key"]=i;
arrayObj.append(item);
}
root["key1"]="value1";
root["key2"]="value2";
root["array"]=arrayObj;
std::string out=root.toStyledString();
std::cout<<out<<std::endl;
getchar();
return 0;
}
注:
如果 JSON 是全局的话,必须手动清除才可以退出程序 否则会释放不了导致崩溃
g_json.clear();
每次取值时应当判断一下类型 类型不对时会崩溃
如:
if(json["int"].isInt()) int i = json["int"].asInt();
json array互转
string as[3][2];
as[0][0] = "1";as[0][1] = "2";
as[1][0] = "3";as[1][1] = "4";
as[2][0] = "5";as[2][1] = "6";
Json::Value root;
for(int i=0; i<3; i++)
{
for(int j=0; j<2; j++)
{
root[IntToString(i)+IntToString(j)] = as[i][j];
}
}
string str = root.toStyledString();
Print(str);
Json::Value root2;
Json::Reader reader;
reader.parse(str, root2);
string as2[3][2];
for(int i=0; i<3; i++)
{
for(int j=0; j<2; j++)
{
as2[i][j] = root2[IntToString(i)+IntToString(j)].asString();
}
}
Print(as2[2][0]);