库之 - Json
2020-04-16 本文已影响0人
googoler
JAVA Json
- jackson
- gson
- fastjson
建议使用 jackson
参考:
C#
- Newtonsoft.Json
C
- CJson
CPP
- JsonCpp
简介:
-
JsonCpp是一个 C++ json 库。
-
所属语言
C++
分析
- C++ json 库
参考:
应用
Json简介
- 键值对 valuestring:value
键值之间的对应关系使用:表示,左边的为 ,右边的为
Json中仅支持两种结构
-
对象(object):name->value键值对(pair)的集合
object可以认为是多个 pair的集合, 其语法是以" "作为object开始,以" "作为object结束,不同的pair之间使用" "分割; -
数组(array): 值的有序表
array是value的有序集合,其语法是以 作为array起始,以 作为array结束,array元素之间使用 分割;
-
stringWrite
#include "json/json.h"
#include <iostream>
/** \brief Write a Value object to a string.
* Example Usage:
* $g++ stringWrite.cpp -ljsoncpp -std=c++11 -o stringWrite
* $./stringWrite
* {
* "action" : "run",
* "data" :
* {
* "number" : 1
* }
* }
*/
int main() {
Json::Value root;
Json::Value data;
constexpr bool shouldUseOldWay = false; //是否使用旧的解释方式
root["action"] = "run";
data["number"] = 1;
root["data"] = data;
if (shouldUseOldWay) {
Json::FastWriter writer;
const std::string json_file = writer.write(root);
std::cout << json_file << std::endl;
} else {
Json::StreamWriterBuilder builder;
const std::string json_file = Json::writeString(builder, root);
std::cout << json_file << std::endl;
}
return EXIT_SUCCESS;
}
-
streamWrite
#include "json/json.h"
#include <iostream>
/** \brief Write the Value object to a stream.
* Example Usage:
* $g++ streamWrite.cpp -ljsoncpp -std=c++11 -o streamWrite
* $./streamWrite
* {
* "Age" : 20,
* "Name" : "robin"
* }
*/
int main() {
Json::Value root;
Json::StreamWriterBuilder builder;
const std::unique_ptr<Json::StreamWriter> writer(builder.newStreamWriter());
root["Name"] = "robin";
root["Age"] = 20;
writer->write(root, &std::cout);
return EXIT_SUCCESS;
}
-
readFromString
#include "json/json.h"
#include <iostream>
/**
* \brief Parse a raw string into Value object using the CharReaderBuilder
* class, or the legacy Reader class.
* Example Usage:
* $g++ readFromString.cpp -ljsoncpp -std=c++11 -o readFromString
* $./readFromString
* colin
* 20
*/
int main() {
const std::string rawJson = R"({"Age": 20, "Name": "colin"})";
const int rawJsonLength = static_cast<int>(rawJson.length());
constexpr bool shouldUseOldWay = false;
JSONCPP_STRING err;
Json::Value root;
if (shouldUseOldWay) {
Json::Reader reader;
reader.parse(rawJson, root);
} else {
Json::CharReaderBuilder builder;
const std::unique_ptr<Json::CharReader> reader(builder.newCharReader());
if (!reader->parse(rawJson.c_str(), rawJson.c_str() + rawJsonLength, &root,
&err)) {
std::cout << "error" << std::endl;
return EXIT_FAILURE;
}
}
const std::string name = root["Name"].asString();
const int age = root["Age"].asInt();
std::cout << name << std::endl;
std::cout << age << std::endl;
return EXIT_SUCCESS;
}
-
readFromStream
#include "json/json.h"
#include <fstream>
#include <iostream>
/** \brief Parse from stream, collect comments and capture error info.
* Example Usage:
* $g++ readFromStream.cpp -ljsoncpp -std=c++11 -o readFromStream
* $./readFromStream
* // comment head
* {
* // comment before
* "key" : "value"
* }
* // comment after
* // comment tail
*/
int main(int argc, char* argv[]) {
Json::Value root;
std::ifstream ifs;
ifs.open(argv[1]);
Json::CharReaderBuilder builder;
builder["collectComments"] = true;
JSONCPP_STRING errs;
if (!parseFromStream(builder, ifs, &root, &errs)) {
std::cout << errs << std::endl;
return EXIT_FAILURE;
}
std::cout << root << std::endl;
return EXIT_SUCCESS;
}
-
读取 Json 字符串
std::string rawJson = str;
const int rawJsonLength = static_cast<int>(rawJson.length());
Json::Value root;
Json::CharReaderBuilder builder;
const std::unique_ptr<Json::CharReader> reader(builder.newCharReader());
if (!reader || !reader->parse(rawJson.c_str(), rawJson.c_str() + rawJsonLength, &root, nullptr))
{
return false;
}
-
Json 对象 转 字符串
Json::Value root;
root["item1"] = "1";
root["item2"] = "2";
std::string request = root.toStyledString();
-
Json 数组
- 完整数组:
Json::Value root;
Json::Value items;
items.append(Json::Value("item1"));
items.append(Json::Value("item2"));
root["other"] = "other";
root["items"] = items;
//数组个数
unsigned int count = root["items"].size();
//循环数组
for (auto var : root["items"]) {
std::string str = var.asString();
}
- 关于Json 空数组类型
Json::Value root;
root["other"] = "other";
root["items"]..resize(0);
-
示例:
Json::Value root;
root["fileName"] = "fileName";
root["parentId"] = u8R"(parentId)"; //C++ 11 新语法
root["remark"] = u8""; //C++ 11 新语法
Json::Value items;
{
Json::Value item;
item["orgType"] = 2;
item["userId"] = "userId";
item["authorizeList"].append(Json::Value("4"));
items.append(item);
}
root["userAuthorizeList"] = items;
string reqData = root.toStyledString();
reqData 的Json字符串为:
reqData