4

我有一个包含 3 个 json 对象的示例文件“sample.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
        }
    }
4

2 回答 2

6

我相信您的 JSON 文件在语法上无效。请参阅www.json.org。您的文件应该包含一个objectarray,例如在您的情况下它应该是这样的:

[{"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 (Json::Value::ArrayIndex i = 0; i != root.size(); i++)
{
    std::string A = root[i].get("A", "ASCII").asString();
    // etc.
}
于 2013-10-25T13:44:01.837 回答
2

这是该问题的解决方案,假设每个对象之间都有换行符(并且没有行是空白或格式错误):

// 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;
}
于 2015-12-07T08:19:03.327 回答