How to parse JSON having dynamic key node

2019-09-20 02:02发布

问题:

How to parse following JSON in iPhone. Key node_10947 may change each time.

Any Idea ?

{
"metadata": {
    "node_10947": {
        "nodeID": "10947",
        "objectID": "11121",
        "name": "Abc",
        "classIdentifier": "folder",
        "node_10948": {
            "nodeID": "10948",
            "objectID": "11122",
            "name": "Abc_A",
            "classIdentifier": "tag"
        },
        "node_10951": {
            "nodeID": "10951",
            "objectID": "11123",
            "name": "Abc_b",
            "classIdentifier": "tag"
        },
        "node_10952": {
            "nodeID": "10952",
            "objectID": "11125",
            "name": "Abc_c ",
            "classIdentifier": "tag"
        }
    },
    "node_170": {
        "nodeID": "170",
        "objectID": "196",
        "name": "XYZ",
        "classIdentifier": "folder",
        "node_179": {
            "nodeID": "179",
            "objectID": "206",
            "name": "XYZ_a",
            "classIdentifier": "tag"
        },
        "node_180": {
            "nodeID": "180",
            "objectID": "207",
            "name": "XYZ_b",
            "classIdentifier": "tag"
        },
        "node_182": {
            "nodeID": "182",
            "objectID": "209",
            "name": "XYZ_c",
            "classIdentifier": "tag"
        }
    }
}

}

I am having the above json and key node may change at any time pls suggest me how can I parse a json whose node is changing dynamically at any time ???

回答1:

Use the framework as pointed by Ehab Amer. For parsing you can use this code snippest

SBJsonParser *sbjasonObj=[[[SBJsonParser alloc]init] autorelease];
NSMutableDictionary *categoriesContainer = [[NSMutableDictionary alloc]initWithDictionary:[sbjasonObj objectWithString:result]];

where result is JSON as your.



回答2:

If it is possible for you to modify that json then include one more key in the json which will hold value of current key like following:

{ "metadata": { currentKey: "node_10947}

And use that key to access values defined by node_10947.

You can use some framework like JSONKit for parsing json as well.