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 <string>  
#include <json.h>
#include <fstream>
#include <memory>
#include <iostream>   
#include <sstream>
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"] = "123456789@qq.com";
	email["163"] = "123456789@163.com";
	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" : "123456789@163.com",
                "QQ" : "123456789@qq.com"
        },
        "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;		//是否结构体
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
JsonCpp是一个用于处理JSON数据的C++库。以下是使用JsonCpp的一些常见用法: 1. 解析JSON字符串 ```cpp #include <json/json.h> #include <iostream> #include <fstream> using namespace std; int main() { ifstream ifs("data.json"); Json::Value root; Json::CharReaderBuilder readerBuilder; JSONCPP_STRING errs; if (!Json::parseFromStream(readerBuilder, ifs, &root, &errs)) { std::cout << errs << std::endl; return 1; } // use root to access json data std::string name = root["name"].asString(); int age = root["age"].asInt(); std::cout << "Name: " << name << std::endl; std::cout << "Age: " << age << std::endl; return 0; } ``` 2. 生成JSON字符串 ```cpp #include <json/json.h> #include <iostream> int main() { Json::Value root; root["name"] = "John"; root["age"] = 30; Json::FastWriter writer; std::string json_str = writer.write(root); std::cout << json_str << std::endl; return 0; } ``` 3. 遍历JSON对象 ```cpp #include <json/json.h> #include <iostream> void printJson(Json::Value &root, int depth = 0) { if (root.isObject()) { std::cout << std::string(depth, ' ') << "{" << std::endl; for (auto it = root.begin(); it != root.end(); ++it) { std::cout << std::string(depth + 4, ' ') << it.name() << ": "; printJson(*it, depth + 4); } std::cout << std::string(depth, ' ') << "}" << std::endl; } else if (root.isArray()) { std::cout << std::string(depth, ' ') << "[" << std::endl; for (auto it = root.begin(); it != root.end(); ++it) { printJson(*it, depth + 4); } std::cout << std::string(depth, ' ') << "]" << std::endl; } else { std::cout << root.asString() << std::endl; } } int main() { std::string json_str = "{\"name\":\"John\",\"age\":30,\"hobbies\":[\"reading\",\"swimming\"]}"; Json::Value root; Json::CharReaderBuilder readerBuilder; JSONCPP_STRING errs; if (!Json::parseFromStream(readerBuilder, json_str, &root, &errs)) { std::cout << errs << std::endl; return 1; } printJson(root); return 0; } ``` 以上是JsonCpp的一些基本用法,更多用法可以参考JsonCpp的文档。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值