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

时间:2013-10-25 11:20:11

标签: 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
        }
    }

2 个答案:

答案 0 :(得分: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"}]

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

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

答案 1 :(得分:1)

这是一个问题的解决方案,假装每个对象之间换行符(并且没有行是空白或格式不正确):

// Very simple jsoncpp test
#include <json/json.h>
#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main(int argc, char *argv[])
{
    Json::Value root;
    Json::Reader reader;
    ifstream test("sample.json", ifstream::binary);
    string cur_line;
    bool success;

    do {
        getline(test, cur_line);
        cout << "Parse line: " << cur_line;
        success = reader.parse(cur_line, root, false);
        cout << root << endl;
    } while (success);

    cout << "Done" << endl;
}