您的位置:首页 > Web前端 > JavaScript

JSCONCPP使用备忘

2015-10-21 14:26 846 查看
使用Jsoncpp生成的lib文件

1、首先下载JSONCPP代码,网站如下:

http://sourceforge.net/projects/jsoncpp/

2、编译jsoncpp-master\jsoncpp-master\makefiles\vs71下的工程代码生成lib文件(jsoncpp-master\jsoncpp-master\build\vs71\debug\lib_json目录下)

3、将lib文件拷到工程目录中,并将jsoncpp-master\jsoncpp-master\include\json目录拷贝到工程目录中

4、工程代码使用时,引用#include "json/json.h"头文件,引入#pragma comment(lib, "json_vc71_libmtd.lib")库就可以使用了

5、编: 检测到“RuntimeLibrary”的不匹配项: 值“MT_StaticRelease”不匹配值“MD_DynamicRelease”。

JSONCPP的lib工程编译选项要和VS工程中的编译选项保持一致。如lib文件工程编译选项为MT(或MTd),VS工程中也要选择MT(或者MTd)否则会出现编译错误问题,debug和release下生成的lib文件名字不同,注意不要看错了

在Release下编译,在工程上右键-》属性-》c/c++-》代码生成-》运行库设置为Multi-threaded Debug (/MTd)

6、测试代码

// JSONCPPTest.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#pragma comment(lib, "json_vc71_libmtd.lib")

#include <fstream>
#include "iostream"
#include <cassert>
#include "json/json.h"
using namespace Json;
using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
/* Test 1 read object {"name" : "小楼一夜听春雨","age" : 27}
ifstream ifs;
ifs.open("testjson.json");
assert(ifs.is_open());

Json::Reader reader;
Json::Value root;
if (!reader.parse(ifs, root, false))
{
return -1;
}

std::string name = root["name"].asString();
int age = root["age"].asInt();

std::cout << name << std::endl;
std::cout << age << std::endl;
*/

// read array [{"name" : "xiaoy", "age" :17} , {"name" : "xiaot", "age" : 20}]
ifstream ifs;
ifs.open("testjson2.json");
assert(ifs.is_open());

Json::Reader reader;
Json::Value root;
if (!reader.parse(ifs, root, false))
{
return -1;
}

std::string name;
int age;
int size = root.size();
for (int i = 0; i < size; ++i)
{
name = root[i]["name"].asString();
age = root[i]["age"].asInt();

std::cout << name << " " << age << std::endl;
}

/*//[{name:"hello world,age:"100"},{name:"James Bill",age:"50"}]
Json::Value root;
Json::FastWriter writer;
Json::Value person;

person["name"] = "hello world";
person["age"] = 100;
person["name"] = Json::Value("Bill Gates");
root.append(person);

Json::Value person2;
person2["name"] = "James Bill";
person2["age"] = 50;
root.append(person2);

std::string json_file = writer.write(root);

ofstream ofs;
ofs.open("testjson3.json");
assert(ofs.is_open());
ofs << json_file;
*/

system("pause");

return 0;
}


使用Jsoncpp包中的.cpp和.h文件



1、将jsoncpp-master整个工程拷贝到工程目录中

2、include\json和src\lib_json目录里的文件包含到VS工程中,在VS工程的属性C/C++下General中Additional
Include Directories包含头文件目录include

3、剩下的使用同上

参考:http://www.cppblog.com/wanghaiguang/archive/2013/12/26/205020.html



内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: