JSONCPP有一个编写器,但它似乎只是从解析器获取信息,然后将其输出到字符串或流中.如何更改或创建新对象,数组,值,字符串等并将其写入文件?
ceg*_*ash 43
#include<json/writer.h>
Run Code Online (Sandbox Code Playgroud)
码:
Json::Value event;
Json::Value vec(Json::arrayValue);
vec.append(Json::Value(1));
vec.append(Json::Value(2));
vec.append(Json::Value(3));
event["competitors"]["home"]["name"] = "Liverpool";
event["competitors"]["away"]["code"] = 89223;
event["competitors"]["away"]["name"] = "Aston Villa";
event["competitors"]["away"]["code"]=vec;
std::cout << event << std::endl;
Run Code Online (Sandbox Code Playgroud)
输出:
{
"competitors" :
{
"away" :
{
"code" : [ 1, 2, 3 ],
"name" : "Aston Villa"
},
"home" :
{
"name" : "Liverpool"
}
}
}
Run Code Online (Sandbox Code Playgroud)
kk-*_*bot 11
#include <json.h>
#include <iostream>
#include <fstream>
void main()
{
std::ofstream file_id;
op_file_id.open("file.txt");
Json::Value value_obj;
//populate 'value_obj' with the objects, arrays etc.
Json::StyledWriter styledWriter;
file_id << styledWriter.write(value_obj);
file_id.close();
}
Run Code Online (Sandbox Code Playgroud)
AFAICT,创建类型的Json ::值,这迎合所有的JSON数据类型的对象,并且将结果传递给一个JSON ::刻录机(及其派生类型之一,是特异性的),或简单地流.
例如:写的三个整数到一个文件中的数组:
Json::Value vec(Json::arrayValue);
vec.append(Json::Value(1));
vec.append(Json::Value(2));
vec.append(Json::Value(3));
std::cout << vec;
Run Code Online (Sandbox Code Playgroud)
Json::StyledWriter已弃用,您可以使用Json::StreamWriterBuilder将 json 写入文件。
Json::Value rootJsonValue;
rootJsonValue["foo"] = "bar";
Json::StreamWriterBuilder builder;
builder["commentStyle"] = "None";
builder["indentation"] = " ";
std::unique_ptr<Json::StreamWriter> writer(builder.newStreamWriter());
std::ofstream outputFileStream("/tmp/test.json");
writer -> write(rootJsonValue, &outputFileStream);
Run Code Online (Sandbox Code Playgroud)
json 将被写入/tmp/test.json.
$ cat /tmp/test.json
{
"foo" : "bar"
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
46636 次 |
| 最近记录: |