6

例如:

    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++ 变量中?

4

1 回答 1

0

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

于 2014-11-12T02:17:36.623 回答