JSONCPP Writing to files

2019-03-09 10:30发布

问题:

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 alter or create new objects, arrays, values, strings, et cetera and write them into the file?

回答1:

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


回答2:

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;


回答3:

#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();
}


回答4:

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.



回答5:

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


标签: c++ json jsoncpp