26

JSONCPP 有一个编写器,但它似乎所做的只是从解析器获取信息,然后将其输出到字符串或流中。如何让它改变或创建新的对象、数组、值、字符串等并将它们写入文件?

4

5 回答 5

49
#include<json/writer.h>

代码:

    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;

输出:

{
        "competitors" : 
        {
                "away" : 
                {
                        "code" : [ 1, 2, 3 ],
                        "name" : "Aston Villa"
                },
                "home" : 
                {
                        "name" : "Liverpool"
                }
        }
}
于 2013-01-08T08:40:58.527 回答
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();
}
于 2015-05-11T19:28:30.327 回答
10

AFAICT,您创建 Json::Value 类型的对象,该对象适用于所有 JSON 数据类型,并将结果传递给 Json::Writer(具体来说,它的派生类型之一),或简单地传递给流。

例如:将三个整数的数组写入文件:

Json::Value vec(Json::arrayValue);
vec.append(Json::Value(1));
vec.append(Json::Value(2));
vec.append(Json::Value(3));
std::cout << vec;
于 2010-11-27T03:45:31.747 回答
8

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

json 将被写入/tmp/test.json.

$ cat /tmp/test.json

{
    "foo" : "bar"
}
于 2018-10-16T14:42:17.173 回答
3

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.

于 2010-11-27T06:43:01.717 回答