如何使用空键/无键的对象创建NSDictionary

时间:2014-09-30 12:24:56

标签: ios objective-c nsdictionary

我想从NSDictionary创建一个JSON字符串。下面给出了要创建的完整JSON。

{
     "source":"point a ",
     "destination":"point b ",
     "boardingPoint":{
           "id":"2222",
           "location":"Some location"
},
"customerName":"test",
"customerLastName":"testing",
"customerEmail":"test@gmail.com",
"blockSeatPaxDetails":[
  {
     "age":"20",
     "name":"test123",
     "sex":"M",
     "title":"Mr",
     "email":"testing@gmail.com"
  }
],
"inventory":0
}

现在我不得不为这个JSON的第一部分创建字典,即

    {
    "source": "point a ",
    "destination": "point b ",
    "boardingPoint": {
    "id": "2222",
    "location": "Some location",

   },

这里boardingPoint是一个字典,它被添加到一个字典中。然后和其他键一起制作一个最终字典。所以当我用objectsAndKeys创建最终字典时,我没有设置键对于第一部分,如下所示。如果我将此@" "设置为空白,则JSON字符串显示为" "为关键。当然,我不能使用nil。那么怎么做?< / p>

如果我插入空白作为第一部分的键

,这就是它的应用方式
  {
  "" : {

    "source" : "point a",
    "boardingPoint" : {
    "id" : "2222",
    "location" : "Some location",
  },
    "destination" : "point b"
 },

这就是我创建词典的方式

  NSDictionary *boardingPoint = [NSDictionary dictionaryWithObjectsAndKeys:boardingPointID,@"id", boardingLocation,@"location",nil];

  NSDictionary *firstDictionary = [NSDictionary dictionaryWithObjectsAndKeys:source,@"source",dest,@"destination",nil];

 NSDictionary *mainDictionary = [NSDictionary dictionaryWithObjectsAndKeys:firstDictionary, @" ",customerName,@"customerName",customerLastName,@"customerLastName",customerEmail,@"customerEmail",blockSeatPaxDetails,@"blockSeatPaxDetails",inventory,@"inventory",nil];

然后当然

     NSData *finalData = [NSJSONSerialization dataWithJSONObject:mainDictionary options:NSJSONWritingPrettyPrinted error:nil];

1 个答案:

答案 0 :(得分:0)

正确缩进的JSON的第一部分是:

{

    "source":"point a ",
    "destination":"point b ",
    "boardingPoint":{
        "id":"2222",
        "location":"Some location",
    },
    "customerName":"test",
    "customerLastName":"testing",
    "customerEmail":"test@gmail.com",
    "blockSeatPaxDetails":[
        {
            "age":"20",
            "name":"test123",
            "sex":"M",
            "title":"Mr",
            "email":"testing@gmail.com",
        },

(你显然已经将某些东西排除在最后,所以我不能放慢最后几行。)

没有&#34;缺少关键&#34;或任何类似的东西。如果您通过NSJSONSerialization提供(无节制的)JSON,它将生成正确的&#34;树&#34;字典和数组。