如何在C ++中使用jsoncpp解析器解析嵌套对象/数组?

时间:2012-10-27 17:11:27

标签: c++ json parsing

例如:

    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]
             }
           ]
 }

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

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

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

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

1 个答案:

答案 0 :(得分:0)

你想要使你的主解析函数递归。然后使用像vector这样的STL类,它允许您为数据动态分配更多存储空间。