我该如何解析这个JSON?

时间:2014-10-19 02:13:37

标签: ios objective-c

将这个JSON对象解析为Objective C中的数据对象的最佳方法是什么?

    {
      "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格式。

2 个答案:

答案 0 :(得分:1)

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

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

其中数据是你的json数据

答案 1 :(得分: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];
相关问题