一、简单介绍
JSON 的全称为:JavaScript Object Notation。
JSON 是用于标记 Javascript 对象的。
JSON 官方的解释为:JSON 是一种轻量级的数据传输格式,我们将它理解为一种数据类型就好。
其格式一般如下(下面程序会有例子):
{
“Name“:“Json”,
"Year":"1994",
"Sex":"MAN",
"Other":
{
"Height":"180",
"Weight":"150"
},
"Parent":
[
{"Father":"C++"},
{"Mother":"C"}
]
}
二、下载JsonCPP,生成可以使用的lib文件
1.从http://jsoncpp.sourceforge.net/下载得到jsoncpp-master.zip,解压
网上的做法:在jsoncpp-src-0.5.0/makefiles/vs71目录里找到jsoncpp.sln,用VS2003及以上版本编译,默认生成静态链接库,本人试了生成不了,于是采用步骤2
2.新建Win32工程,命名为JsonLib,应用程序类型选择静态库,取消预编译头,如下
2.将jsoncpp-master文件夹中的include中的Json文件夹复制到你的工程目录下
3.将jsoncpp-master文件夹中的src中的lib_json文件夹中的文件复制到你的工程目录下,最终工程拥有的文件如下:
4.如下图将对应文件引入工程
5.生成-重新生成解决方案,即可生成所需的JsonLib.lib
三、C++调用Jsoncpp
1.新建控制台程序工程JsonTest
2.将jsoncpp-master文件夹中的include中的Json文件夹和JsonLib.lib复制到你的工程目录下
3.项目-属性-链接器-输入-附件依赖项,添加JsonLib.lib
4.如下图将对应文件引入工程
5.JsonTest.cpp的代码如下:
#include "stdafx.h"
#include "json/json.h"
#include <iostream>
using namespace std;
using namespace std;
Json::Reader reader;
Json::Value value;
int _tmain(int argc, _TCHAR* argv[])
{
string strValue = "{\"name\":\"json\",\"Year\":1994,\"Sex\":\"Man\",\"others\":{\"Height\":180,\"Weight\":150},\"Parents\":[{\"Father\":\"C++\"},{\"Mother\":\"C\"}]}";
if (reader.parse(strValue, value))
{
Json::FastWriter fast_writer;
cout << fast_writer.write(value) <<endl;
string out = value["name"].asString();
cout<<out <<endl;
out = value["Year"].asString();
cout<<out <<endl;
out = value["Sex"].asString();
cout<<out <<endl;
out = value["others"]["Height"].asString();
cout<<out <<endl;
out = value["others"]["Weight"].asString();
cout<<out <<endl;
const Json::Value arrayObj = value["Parents"];
for (unsigned int i = 0; i < arrayObj.size(); i++)
{
if (arrayObj[i].isMember("Father"))
{
out = arrayObj[i]["Father"].asString();
cout<<out <<endl;
}
if (arrayObj[i].isMember("Mother"))
{
out = arrayObj[i]["Mother"].asString();
cout<<out <<endl;
}
}
}
Json::Value json_temp;
json_temp["Height"] = Json::Value(180);
json_temp["Weight"] = Json::Value(150);
Json::Value Parents,Mother,Father;
Father["Father"] = Json::Value("C++");
Mother["Mother"] = Json::Value("C");
Parents.append(Father);
Parents.append(Mother);
Json::Value root;
root["name"] = Json::Value("json");
root["Year"] = Json::Value(1994);
root["Sex"] = Json::Value("Man");
root["others"] = json_temp;
root["Parents"] = Parents;
Json::FastWriter fast_writer;
cout << fast_writer.write(root) <<endl;
return 0;
}