JSONCPP Writing to files

﹥>﹥吖頭↗ 提交于 2019-12-02 18:08:08
#include<json/writer.h>

Code:

    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;

Output:

{
        "competitors" : 
        {
                "away" : 
                {
                        "code" : [ 1, 2, 3 ],
                        "name" : "Aston Villa"
                },
                "home" : 
                {
                        "name" : "Liverpool"
                }
        }
}
#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();
}

AFAICT, you create objects of type Json::Value, which caters for all the JSON data-types, and pass the result to a Json::Writer (one of its derived types, to be specific), or simply to a stream.

E.g.: to write an array of three integers to a file:

Json::Value vec(Json::arrayValue);
vec.append(Json::Value(1));
vec.append(Json::Value(2));
vec.append(Json::Value(3));
std::cout << vec;

First, you have to create the desired JSON::Value. You should look at all the constructors (first). To create the necessary hierarchies, see append and the operator[] overloads; there are overloads for both array indices and string keys for objects.

One way to write the JSON value back out is using StyledStreamWriter::write and ofstream.

See cegprakash's answer for how to write it.

Json::StyledWriter is deprecated, you can use Json::StreamWriterBuilder to write json into files.

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);

The json will be written into /tmp/test.json.

$ cat /tmp/test.json

{
    "foo" : "bar"
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!