json编译和使用

1、最新的下载地址 https://github.com/open-source-parsers/jsoncpp

此版本最好用vs2010以上版本编译 。

用vs2008由于缺失stdint.h导致编译失败,网上大神自定义头文件的方式 

#ifdef _MSC_VER  
typedef __int32 int32_t; 
typedef unsigned __int32 uint32_t; 
typedef __int64 int64_t; 
typedef unsigned __int64 uint64_t;  
#else 
#include <stdint.h> 
#endif 

  

Visual Studio 2003 - 2008 (Visual C++ 7.1 - 9) don't claim to be C99 compatible

不过试了,不好用。

所以直接用vs2010以上编译了,此版本以上自带 stdint.h 头文件

2、解压之后 打开  jsoncpp-master\makefiles\msvc2010\jsoncpp.sln  编译即可。


3、使用demo

//工程属性 ->c/c++ ->代码生成->运行库->记得要和生成的lib_json.lib选项一致,
//我这里是多线程调试 (/MTd) 否则编译不过的!!


#include "stdafx.h"
#include "json\json.h"
#include<string>
#include<iostream>
#include <memory>
#include<fstream>

using namespace std;
#pragma comment(lib, "lib_json.lib")


int main()
{
	Json::Value val;
	Json::StreamWriterBuilder style_write;

	val["name"] = "xiaoli";
	val["age"] = 10;
	val["class"] = "class2";
	//设置默认格式
	style_write["commentStyle"] = "None";
	style_write["indentation"] = "";
	std::unique_ptr<Json::StreamWriter> writer(style_write.newStreamWriter());

	std::ofstream ofs;
	ofs.open("result.json", std::ios::app);
	writer->write(val, &ofs);
	ofs.close();

	Json::Reader read;

	//从文件中读取,保证当前文件有test.json文件
	std::ifstream in("result.json", ios::binary);

	if (!in.is_open())
	{
		cout << "Error opening file\n";
		return -1;
	}
	Json::Value root;
	if (read.parse(in, root))
	{
		std::string name = root["name"].asString();
		int nAge = root["age"].asInt();
		std::string class_name = root["class"].asString();

		cout << "name: " << name.c_str() << " age: " << nAge << " class: " << class_name.c_str() << endl;
	}
	in.close();
    return 0;
}




评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值