2014-10-19 138 views
-4

將這個JSON對象解析爲Objective C中的數據對象的最佳方法是什麼?我應該如何解析這個JSON?

{ 
     "Properties" : { 
     "Property1" : { 
      "min" : 70.0, 
      "max" : 70.0 
     }, 
     "Property2" : { 
      "min" : 0.41, 
      "max" : 0.41 
     }, 
     "Property3" : { 
      "min" : 0.41, 
      "max" : 0.41 
     }, 
     "Property4" : { 
      "min" : 0.41, 
      "max" : 0.41 
     } 
    } 

名稱「屬性」將保持不變,但其中的屬性名稱可以更改,屬性的數量也可以更改。例如,這可能是;

{ 
    "Properties": 
     "RandomNameOfProperty" : { 
      "min" : 0.41, 
      "max" : 0.41 
     }, 
     "RandomNameOfProperty2" : { 
      "min" : 0.41, 
      "max" : 0.41 
     } 
    } 
} 

編輯:更正了JSON格式。

+3

這不是有效的JSON。有效的JSON始終以'['或'{'開頭。 – 2014-10-19 03:37:00

+0

JSON以{開頭。 – fallen 2014-10-20 02:23:51

回答

1
NSMutableDictionary *json = [[NSMutableDictionary alloc] init]; 

json = [NSJSONSerialization JSONObjectWithData: data options: NSJSONReadingMutableLeaves error: &e]; 

,其中數據是你的JSON數據

+0

不是我們不能確定最外層的結構是字典,因爲OP沒有提供競爭的JSON。 – 2014-10-19 18:41:46

+0

最外層的結構永遠不會是一個數組。 – fallen 2014-10-20 02:21:43

0

這裏是你如何改變你的JSON到Objective-C

NSString *jsonString = @"{"name": "My name" ....}" 
    NSData *data = [@" " dataUsingEncoding:NSUTF8StringEncoding]; 
    NSMutableDictionary *json = [[NSMutableDictionary alloc] init]; 
    NSError *er; 
    json = [NSJSONSerialization JSONObjectWithData: data options: NSJSONReadingMutableLeaves error: &er]; 

    MyClassModel *my = [[MyClassModel alloc] init]; 
    my.name = json[@"name"]; 
    my.age = [json[@"age"] integerValue]; 
    my.type = json[@"type"]; 

也有做動態解析和轉換爲你許多圖書館。
JSONModel真的很不錯。有了它,你的代碼看起來像這樣 -

NSString* json = @"{"name": "My name" ....}" //(fetch here JSON from Internet) 
NSError* err = nil; 
MyClassModel* country = [[MyClassModel alloc] initWithString:json error:&err];