JsonCpp的用法

时间:2019/8/5
天气:阴转晴

今早依然被热醒 不知为何今天周一比往常的地铁人格外的多 挤了好几次 哈哈

JsonCpp的用法

JSONCPP是C++中的生成与解析JSON 字符串的一种实现。JSON是一种人比较容易理解,机器也比较容易解析的轻量级的数据交换格式。可以从Github上下载jsoncpp,https://github.com/open-source-parsers/jsoncpp

如何使用

将解压文件中JsonCpp\jsoncpp-master\include中的文件拷贝进你的工程中使用
代码下载

新API

生成JSON字符串

#include   
#include 
#include 
#include 
#include    
#include 
using namespace std;
string f_createJson()
{
	std::string jsonStr;
	Json::Value root, lang, email;
	Json::StreamWriterBuilder writerBuilder;
	ostringstream os;

	root["Name"] = "OYH";
	root["Age"] = 23;

	lang[0] = "C++";
	lang[1] = "C";
	root["Language"] = lang;

	email["QQ"] = "[email protected]";
	email["163"] = "[email protected]";
	root["E-mail"] = email;

	unique_ptr<Json::StreamWriter> jsonWriter(writerBuilder.newStreamWriter());
	jsonWriter->write(root, &os);
	jsonStr = os.str();

	cout << "Json:\n" << jsonStr << endl;
	return jsonStr;
}

调用这个函数会输出

Json:
{
        "Age" : 23,
        "E-mail" :
        {
                "163" : "[email protected]",
                "QQ" : "[email protected]"
        },
        "Language" :
        [
                "C++",
                "C"
        ],
        "Name" : "OYH"
}

解析JSON字符串

bool f_parseJson(const string &info)
{
	if (info.empty())
	{
		return false;
	}

	bool res;
	JSONCPP_STRING errs;
	Json::Value root, lang, email;
	Json::CharReaderBuilder readerBuilder;

	unique_ptr<Json::CharReader> const jsonReader(readerBuilder.newCharReader());

	res = jsonReader->parse(info.c_str(),info.c_str() + info.length(),&root,&errs);
	if (!res || !errs.empty())
	{
		cout << "parseJson err." << errs << endl;
	}

	cout << "Name:" << root["Name"].asString() << endl;
	cout << "Age:" << root["Age"].asInt() << endl;

	lang = root["Language"];
	cout << "Language:";
	for (int i = 0;i<lang.size();i++)
	{
		cout << lang[i]<< " ";
	}

	cout << endl;

	email = root["E-mail"];
	cout << "QQ:" << email["QQ"].asString() << endl;
	cout << "163:" << email["QQ"].asString() << endl;
	return res;
}

调用解析之后结果如下:

Name:OYH
Age:23
Language:"C++" "C"
QQ:123456789@qq.com
163:123456789@qq.com

旧版本API

坚持使用旧API可以在文件头部加入这段代码:

#if defined(__GNUC__)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
#elif defined(_MSC_VER)
#pragma warning(disable : 4996)
#endif

创建JSON

	//旧版本API生成JSON
string f_createJsonOld()
{
	Json::Value root, ex;
	Json::FastWriter writer;

	root["Name"] = "Lucy";
	root["age"] = 20;
	ex[0] = "ABC";
	ex[1] = "DEF";
	root["exinfo"] = ex;

	string json = writer.write(root);
	return json;
}

调用之后结果如下:

Json:
{
 "Age":20,
 "Name":"Lucy",
 "exinfo":["ABC","DEF"]
}

解析JSON

	Json::Reader reader;
	Json::Value root;
	const char *jsonStr = "{\"Name\":\"Lucy\",\"Age\":20}";
	
	if (!reader.parse(jsonStr, jsonStr + strlen(jsonStr), root)) {
        std::cout << "json parse failed\n";
        return 1;
    }

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

调用之后结果如下:

Name:Lucy
Age:20
exinfo:ABC
exinfo:DEF

总结

可以把Json::Value理解为一个·Json结构,这个类可以嵌套,也可以当做数组一样使用,在需要的时候可以把这个结构转换为相应的类型
Json::Value其他的成员函数还有

//类型转换
Int asInt() const;
UInt asUInt() const;
Int64 asInt64() const;
UInt64 asUInt64() const;
LargestInt asLargestInt() const;
LargestUInt asLargestUInt() const;
float asFloat() const;
double asDouble() const;
bool asBool() const;
// 检测类型
bool isNull() const;
bool isBool() const;
bool isInt() const;
bool isInt64() const;
bool isUInt() const;
bool isUInt64() const;
bool isIntegral() const;
bool isDouble() const;
bool isNumeric() const;
bool isString() const;		//字符串
bool isArray() const;		//是否是数组
bool isObject() const;		//是否结构体

你可能感兴趣的:(c++)