如何解析一个字符串数组(JSON) - iOS?

时间:2014-08-22 07:51:33

标签: ios objective-c arrays json parsing

我的JSON是这样的:

{
  "categories":["Love", "Hope, "Dreams"],
}

我熟悉使用对象解析数组或字典,但我对如何解析一个充满字符串的数组感到困惑。我该怎么做?

2 个答案:

答案 0 :(得分:2)

使用以下自定义方法

-(NSArray *)stringArrayFromJsonFile:(NSString *)jsonFileName withKey:(NSString *)key
{
    NSData *fileContents = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:jsonFileName ofType:@"json"]];
    NSError *error;

    NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:fileContents options:kNilOptions error:&error];

    NSArray * stringArray = [dict objectForKey:key];

    return stringArray;
}

现在称该方法为

NSArray* stringArray =  [self stringArrayFromJsonFile:@"yourJsonFileName" withKey:@"categories"];

答案 1 :(得分:2)

您应该先获取数据。

    NSString * JSONString = @"{\"somekey\":[\"somevalue\"]}";
    NSData * JSONData = [JSONString dataUsingEncoding:NSUTF8StringEncoding];

    id JSONResult = [NSJSONSerialization JSONObjectWithData:JSONData options:NSJSONReadingAllowFragments error:nil];

    if ([JSONResult isKindOfClass:[NSDictionary class]]) {
        NSDictionary * dictionary = JSONResult;
    } else {
        ...
    }