0

如何向 json 文件添加多个密钥?

NSArray *keys = [NSArray arrayWithArray:allkeys];
NSArray *objects = [NSArray arrayWithArray:allobjects];

NSDictionary *jsonDictionary = [NSDictionary dictionaryWithObjects:objects forKeys:keys];

正如您在上面看到的,jsonDictionary 的键是键,但我想要一个里面有更多键的键。我尝试了“forKeys:keys,keys2”(keys2 另一个数组,但不起作用。现在这是结果:

{"text2":"Untitled {{400, 100}, {200, 100}} <UICFFont: 0x2c3960> font-family: \"Helvetica\"; font-weight: normal; font-style: normal; font-size: 12px","text3":"Untitled {{400, 100}, {200, 100}} <UICFFont: 0x2c3960> font-family: \"Helvetica\"; font-weight: normal; font-style: normal; font-size: 12px","text1":"Untitled {{400, 100}, {200, 100}} <UICFFont: 0x2c3960> font-family: \"Helvetica\"; font-weight: normal; font-style: normal; font-size:     12px"}

数组键包含 Text1、text2... 数组对象包含 Untitled、size... 但我想要一个键“text1”,里面有“text writing”、“size”... 不是全部在一起。

可能是这样的:

{  
"menu": {  
    "header": "xProgress SVG Viewer",  
    "items": [  
        {  
            "id": "Open"  
        },  

在此先感谢您的帮助

4

1 回答 1

1

您必须创建嵌套 NSDictionaries 的层次结构才能实现您想要做的事情。

像这样的东西:

// the following objecst are just dummies, fill this with your own objects
NSArray *objectArray = [NSArray arrayWithOjects:obj1,obj2,obj3,nil];
NSArray *keyArray = [NSArray arrayWithOjects:@"key1",@"key2,@"key3",nil];

NSDictionary *subDict = [NSDictionary dictionaryWithObjects:objectArray forKeys:keyArray];

// now create the main dictionary, which will hold your sub dictionary for one key
objectArray = [NSArray arrayWithObjects:,subDict,someObject,@"just a string"];
keyArray = [NSArray arrayWithObjects:@"first key",@"second key",@"third key"];

NSDictionary *mainDict = [NSDictionary dictionaryWithObjects:objectArray forKeys:keyArray];

您的示例 JSON 将具有以下结构:

一个带有键“菜单”的 NSDictionary,其中包含另一个 NSDictionary。这个字典有键“header”,它包含一个字符串,以及键“items”,它包含一个 NSDictionaries 的 NSArray。

于 2012-05-06T16:23:02.590 回答