[英]Keyless NSDictionary from NSArray
我正在嘗試創建看起來像的JSON
[
{
property1 = "test1",
property2 = "test2",
},
{
property1 = "test1",
property2 = "test2",
},
...
]
到目前為止,我使用NSDictionary所能獲得的就是:
[
key1 = {
property1 = "test1",
property2 = "test2",
},
key 2 = {
property1 = "test1",
property2 = "test2",
},
...
]
...這不好。 有沒有一種簡單的方法可以在NSDictionary中創建無鍵數組?
嘗試:
NSArray *objects = @[
@{ @"property1": @"test1", @"property2": @"test2" },
@{ @"property1": @"test1", @"property2": @"test2" }
];
NSError *error = nil;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:objects options:0 error:&error];
看起來您使用的是NSDictionary
作為根對象,而不是NSArray
。
您的JSON無效。 要么應該是這樣的JSON數組:
[
{
property1 : "test1",
property2 : "test2",
},
{
property1 : "test1",
property2 : "test2",
},
...
]
或嵌入了其他對象的JSON對象,盡管在這種情況下,您需要指定屬性的名稱:
{
obj1 : {
property1 : "test1",
property2 : "test2",
},
obj2 : {
property1 : "test1",
property2 : "test2",
},
...
}
第一種情況映射到NSDictionary的NSArray,第二種情況映射到具有兩個鍵(obj1,obj2,)的NSDictionary,每種情況都映射到具有兩個鍵(屬性1,property2)的NSDictionary。
根據對問題的編輯判斷,您需要序列化此對象,以獲得所需的結構:
NSArray * dataForJSON = @[
@{
@"property1" : @"test1",
@"property2" : @"test2"
},
@{
@"property1" : @"test1",
@"property2" : @"test2"
}
];
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.