开发者

JSONCPP Writing to files

JSONCPP has a writer, but all it seems to do is get info from the parser and then output it into a string or a stream. How do I make it al开发者_如何学Goter or create new objects, arrays, values, strings, et cetera and write them into the file?


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


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"
}


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜