2013-11-27 49 views
-1

我試圖創建的JSON看起來像門鎖的NSDictionary的NSArray從

[ 
    { 
     property1 = "test1", 
     property2 = "test2", 
    }, 
    { 
     property1 = "test1", 
     property2 = "test2", 
    }, 
    ... 
] 

到目前爲止,所有我能得到使用的NSDictionary是這樣的:

[ 
    key1 = { 
     property1 = "test1", 
     property2 = "test2", 
    }, 
    key 2 = { 
     property1 = "test1", 
     property2 = "test2", 
    }, 
    ... 
] 

...這是沒有好。有沒有一種簡單的方法在NSDictionary中創建無鍵數組?

+3

使用'NSArray'? – 2013-11-27 09:36:29

+0

是什麼類型?你使用的是什麼JSON編碼器?你可以向我們展示反序列化代碼+ NSLog類型的你從JSON中獲得什麼 –

+0

讓我看看你創建JSON的代碼 – manujmv

回答

2

嘗試:

NSArray *objects = @[ 
    @{ @"property1": @"test1", @"property2": @"test2" }, 
    @{ @"property1": @"test1", @"property2": @"test2" } 
]; 

NSError *error = nil; 
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:objects options:0 error:&error]; 

看起來像你正在使用的,而不是一個NSArray一個NSDictionary爲根對象。

+0

訣竅了。我只將NSData解碼爲NSSrting。 –

2

您的JSON無效。無論是它應該是一個JSON數組是這樣的:

[ 
    { 
     property1 : "test1", 
     property2 : "test2", 
    }, 
    { 
     property1 : "test1", 
     property2 : "test2", 
    }, 
    ... 
] 

或嵌入其他對象的JSON對象,但在這種情況下,你就需要指定屬性的名稱:

{ 
    obj1 : { 
     property1 : "test1", 
     property2 : "test2", 
    }, 
    obj2 : { 
     property1 : "test1", 
     property2 : "test2", 
    }, 
    ... 
} 

第一大小寫映射到NSDictionaries的NSArray,而第二個映射到帶有兩個鍵(obj1,obj2,)的NSDictionary,每個映射到每個具有兩個鍵(property1,property2)的NSDictionary。

來看由編輯您的問題做出,你需要序列化這個對象,以獲得所需的結構:

NSArray * dataForJSON = @[ 
    @{ 
     @"property1" : @"test1", 
     @"property2" : @"test2" 
    },   
    @{ 
     @"property1" : @"test1", 
     @"property2" : @"test2" 
    } 
];