2014-10-19 135 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];