如何使用jsoncpp读取多个json对象

Rag*_*ull 4 c++ json jsoncpp

我有一个示例文件"sample.json",其中包含3个json对象

{ "A": "something1", "B": "something2", "C": "something3", "d": "something4"} { "A": "something5", "B": "something6", "C": "something7", "d": "something8"} { "A": "something9", "B": "something10", "C": "something11", "d": "something12"}

(上面的文件中没有换行符)

我想用jsoncpp读取所有三个json对象.

我能够读取第一个对象但不能读取它.

这是我的代码的相关部分

    Json::Value root;   // will contains the root value after parsing.
    Json::Reader reader;
    std::ifstream test("sample.json", std::ifstream::binary);
    bool parsingSuccessful = reader.parse(test, root, false);
    int N = 3;
    if (parsingSuccessful)
    {
         for (size_t i = 0; i < N; i++)
         {
                std::string A= root.get("A", "ASCII").asString();
                std::string B= root.get("B", "ASCII").asString();
                std::string C= root.get("C", "ASCII").asString();
                std::string D= root.get("D", "ASCII").asString();
               //print all of them
        }
    }
Run Code Online (Sandbox Code Playgroud)

小智 6

我相信你的JSON文件在语法上是无效的.见www.json.org.您的文件应包含单个对象数组,例如在您的情况下它应该是这样的:

[{"A":"something1","B":"something2","C":"something3","D":"something4"},
 {"A":"something5","B":"something6","C":"something7","D":"something8"}, 
 {"A":"something9","B":"something10","C":"something11","D":"something12"}]
Run Code Online (Sandbox Code Playgroud)

然后,您可以在循环中访问数组的每个对象:

for (size_t i = 0; i < root.size(); i++)
{
    std::string A = root[i].get("A", "ASCII").asString();
    // etc.
}
Run Code Online (Sandbox Code Playgroud)