JSONCPP Writing to files

杀马特。学长 韩版系。学妹 提交于 2019-12-20 09:29:41

问题


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:


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



回答3:


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;



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


来源:https://stackoverflow.com/questions/4289986/jsoncpp-writing-to-files

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