通过JsonCpp读Json string的方法看这里:https://www.jianshu.com/p/0a631408f8a4
本文介绍一下写Json string的方法。
1 转换Json object为string
JsonCpp提供的老接口为:
class JSON_API FastWriter : public Writer {
public:
JSONCPP_STRING write(const Value& root);
使用此接口将Json数据转换为string的源代码为:
#include <iostream>
#include <string>
#include <jsoncpp/json/json.h>
int main()
{
Json::Value root;
root["Name"] = Json::Value("Tom");
root["Age"] = Json::Value(20);
root["Children"].append("Peter");
root["Children"].append("John");
Json::FastWriter writer;
std::string str = writer.write(root);
std::cout << str << std::endl;
return 0;
}
编译运行:
$ g++ e.cpp -l jsoncpp && ./a.out
{"Age":20,"Children":["Peter","John"],"Name":"Tom"}
如果将FastWrite
改为StyledWrite
,可以得到带格式的Json字符串。
2 使用新接口
Json::FastWriter writer;
std::string str = writer.write(root);
上面是旧接口,可以完全用下面的新接口替换掉:
Json::StreamWriterBuilder builder;
std::string str = Json::writeString(builder, root);
看一下完整的代码:
#include <iostream>
#include <string>
#include <jsoncpp/json/json.h>
int main()
{
Json::Value root;
root["Name"] = Json::Value("Tom");
root["Age"] = Json::Value(20);
root["Children"].append("Peter");
root["Children"].append("John");
// Json::FastWriter writer;
// std::string str = writer.write(root);
Json::StreamWriterBuilder builder;
std::string str = Json::writeString(builder, root);
std::cout << str << std::endl;
return 0;
}
编译运行:
$ g++ e1.cpp -l jsoncpp && ./a.out
{
"Age" : 20,
"Children" :
[
"Peter",
"John"
],
"Name" : "Tom"
}
4 构造维基百科的Json数据
#include <iostream>
#include <string>
#include <jsoncpp/json/json.h>
int main()
{
Json::Value root;
root["firstName"] = Json::Value("John");
root["lastName"] = Json::Value("Smith");
root["sex"] = Json::Value("male");
root["age"] = Json::Value(25);
Json::Value address;
address["streetAddress"] = Json::Value("21 2nd Street");
address["city"] = Json::Value("New York");
address["state"] = Json::Value("NY");
address["postalCode"] = Json::Value("10021");
root["address"] = Json::Value(address);
Json::Value home_phone;
Json::Value fax;
home_phone["type"] = Json::Value("home");
home_phone["number"] = Json::Value("212 555-1234");
fax["type"] = Json::Value("fax");
fax["number"] = Json::Value("646 555-4567");
root["phoneNumber"].append(home_phone);
root["phoneNumber"].append(fax);
Json::StreamWriterBuilder builder;
std::string str = Json::writeString(builder, root);
std::cout << str << std::endl;
return 0;
}
编译运行:
$ g++ h.cpp -l jsoncpp && ./a.out
{
"address" :
{
"city" : "New York",
"postalCode" : "10021",
"state" : "NY",
"streetAddress" : "21 2nd Street"
},
"age" : 25,
"firstName" : "John",
"lastName" : "Smith",
"phoneNumber" :
[
{
"number" : "646 555-4567",
"type" : "fax"
},
{
"number" : "212 555-1234",
"type" : "home"
}
],
"sex" : "male"
}
5 参考
使用JsonCpp解析Json string https://www.jianshu.com/p/0a631408f8a4
网友评论