官方示例1.9.4
readFromStream
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;
readFromString
const std::string rawJson = R"({"Age": 20, "Name": "colin"})";
const auto 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;
streamWrite
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);
stringWrite
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;
}
下面是我写的
// jsoncpp_test.cpp : 定义控制台应用程序的入口点。
//
//更新时间2020.02.18
#include "stdafx.h"
#include "map"
#include <string>
#include "windows.h"
#include "Json.h"
int main()
{
//写入json文件
Json::StreamWriterBuilder WriteBuilder;
auto_ptr<Json::StreamWriter> writer(WriteBuilder.newStreamWriter());
//Json::CharReader* reader(b.newCharReader());
Json::Value jsonLine;
jsonLine["qqq"] = 111;
jsonLine["www"] = 222;
//jsonLine["eee"] = 333;//不能这样使用,会报错,名称[""][""]必须完整
jsonLine["eee"]["aaa"] = 333;
jsonLine["eee"]["bbb"] = 444;
ofstream outtofile;
outtofile.open("F:\\json\\jsoncpp_test\\Debug\\test.json");
writer->write(jsonLine, &outtofile);
outtofile.close();
//test.json内容如下
//{
// "eee" :
// {
// "aaa" : 333,
// "bbb" : 444
// },
// "qqq" : 111,
// "www" : 222
//}
//读取json文件内容
//Json::Value jsonLine;
Json::CharReaderBuilder readbuilder;
auto_ptr<Json::CharReader> reader(readbuilder.newCharReader());
//Json::CharReader *reader = builder.newCharReader();
JSONCPP_STRING errs;
ifstream is;
is.open("F:\\json\\jsoncpp_test\\Debug\\test.json");
if (Json::parseFromStream(readbuilder, is, &jsonLine, &errs) && is.is_open())
{
string a= jsonLine["qqq"].asString();
int b = jsonLine["www"].asInt();
double c = jsonLine["eee"]["aaa"].asDouble();
float d = jsonLine["eee"]["bbb"].asFloat();
}
return 0;
}