如何读取*.json
文件并将输出放在std::string
上?如何使用rapidjson读取json文件并输出到std :: string?
我有这个样本,但我总是得到null
在std::string
。
#include <rapidjson/document.h>
#include <rapidjson/istreamwrapper.h>
#include "rapidjson/writer.h"
#include "rapidjson/stringbuffer.h"
#include <rapidjson/ostreamwrapper.h>
#include <fstream>
#include <iostream>
using namespace rapidjson;
using namespace std;
void main()
{
ifstream ifs("input.json");
IStreamWrapper isw(ifs);
Document d;
d.ParseStream(isw);
StringBuffer buffer;
Writer<StringBuffer> writer(buffer);
d.Accept(writer);
std::string jsonStr(buffer.GetString());
if(jsonStr == "null")
std::cout << "is null..." << std::endl; //<--always here!
else
{
std::cout << jsonStr.c_str() << std::endl;
d["ip"] = "123456789";
ofstream ofs("output.json");
OStreamWrapper osw(ofs);
Writer<OStreamWrapper> writer2(osw);
d.Accept(writer2);
}
}
这是我的JSON文件:
{
"ip" : "192.168.0.100",
"angle x": 20,
"angle y": 0,
"angle z": 0
}
你到底想实现什么呢?如果你想将整个文件读入'string',那么你不需要一个quickjson。 – Heavy
我想从文件中读取,更改json上的一些字段,写回到另一个文件。 – waas1919
@ waas1919:你的文件'input.json'包含什么?在这里发布最小有效的JSON。您是否使用[HasParseError()](http://rapidjson.org/classrapidjson_1_1_generic_document.html#a7607bb42b51547e44bfd4cab35d8f20e)和[GetParseError()](http://rapidjson.org/classrapidjson_1_1_generic_document.html#ab94c280c079a6837a24951cb4d8f337b)验证您的解析是否成功? ? – Azeem