【问题标题】:How to Parse an Array of Strings (JSON) - iOS?如何解析字符串数组 (JSON) - iOS?
【发布时间】:2014-08-22 07:51:33
【问题描述】:

我的 JSON 格式如下:

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

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

【问题讨论】:

  • NSArray *categories = [json valueForKey:@"categories"];然后 NSString *love = categories[0];

标签: ios objective-c arrays json parsing


【解决方案1】:

使用以下自定义方法

-(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"];

【讨论】:

  • 当您想从应用程序主包中的 json 文件获取数据时,上述代码有效
【解决方案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 {
        ...
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多