【问题标题】:How parse nested object/array using jsoncpp parser in C++?如何在 C++ 中使用 jsoncpp 解析器解析嵌套对象/数组?
【发布时间】:2012-10-17 15:02:59
【问题描述】:

例如:

    Json::Reader reader;
    Json::Value val;
    ifstream file("JSON/test.json");
    bool success = reader.parse(file, val, false);
    vector<string> obj = val.getMemberNames();

    for (int i = 0; i < val.size(); i++)
    {
        // switch type of value
        switch (val.get(obj.at(i), "default").type())
        {
            case stringValue:
                cout << "I'm string" << endl;
                ... need to save **membername** and **value**
                break;
            case intValue:
                cout << "I'm int"  << endl;
                ... need to save **membername** and **value**
                break;
            case nullValue:
                cout << "I'm null"  << endl;
                break;
            case arrayValue:
                 ... code to parse an array (with nested sure) ...
                 ... need to save
                break;
            case objectValue:
                ... code to parse an object (with nested sure) ...
                ... need to save 
                break;
        }
    }

示例 JSON 文件 (JSON/test.json):

{
    "layout": "fit",
    "xtype": "viewport",
    "height": 200,
    "style": {
                "backgroundColor": "46f0a8"
             },

           "items": 
           [
             {
                "title": "Management Console",
                "padding": "10 10 10 10",
                "bodyPadding": 10,
                "autoScroll": true,
                "items2": [1, 2, 3]
             }
           ]
 }

在数组items中,我们可以看到另一个名为items2的数组(嵌套)。

对于数组可能会遇到以下情况:

array[Jacob, Joseph] or
array[{name: Jacob, name: Joseph}] or
array[{name: Jacob}, {name: Joseph}]

对于对象,它是相似的。在每个字段中,当然可以是许多嵌套的对象/数组。如何将数据保存在 C++ 变量中?

【问题讨论】:

  • 我很不清楚,你到底要什么。我看到3个问题。如何处理jsoncpp 库中的array 数据和object 数据?如何适应不同的数据存储约定?如何处理一般/嵌套案例?
  • 不清楚是要解析成预定义的 C++ 类,还是要解析任意 JSON 数据。对于后一种情况,将JSON::Value 转换为其他格式确实没有意义;直接使用JSON::Value即可。

标签: c++ json parsing


【解决方案1】:

您需要使您的主要解析函数递归。然后使用像 vector 这样的 STL 类,让您可以为数据动态分配更多存储空间。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-05-18
    • 2018-09-02
    • 1970-01-01
    • 1970-01-01
    • 2019-01-21
    • 1970-01-01
    • 2012-02-21
    相关资源
    最近更新 更多