2014-09-30 62 views
-1

我想從NSDictionary創建JSON字符串。下面給出了要創建的完整JSON。如何使用空白鍵/無對象的鍵創建NSDictionary

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

現在我停留在這個JSON即

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

    }, 

這裏boardingPoint的第一部分創建字典是被添加到一個dictionary.And然後用鑰匙的其餘部分一起字典我做了一個最終字典。因此,當我創建最終字典時,用objectsAndKeys我沒有爲第一部分設置密鑰,如下所示。如果我將此空白設置爲@" ",則JSON字符串顯示" "爲關鍵字。並且當然,我不能使用nil。那麼怎麼做呢?

這是怎麼apppears如果我插入空白作爲第一部分關鍵

{ 
    "" : { 

    "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]; 

,然後ofcourse

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

你完全混淆了縮進。 – 2014-09-30 12:28:10

+0

是的,我知道這一點。迄今爲止編輯它是最好的。 – iSD 2014-09-30 12:31:48

+0

[NSNull Null] for NSD在NSDictionaries或NSArrays中 – 2014-09-30 12:33:07

回答

0

JSON的第一部分正確縮進:

{ 

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

(你顯然省略掉朝着端的東西,所以我可以在最後幾行不慢。)

沒有「丟失鑰匙」或諸如此類的事。如果您通過NSJSONSerialization提供您的(uriided)JSON,它將生成正確的字典和數組「樹」。

相關問題