美文网首页
iOS Json和NSDictionary、NSArray 互转

iOS Json和NSDictionary、NSArray 互转

作者: 何以_aaa | 来源:发表于2019-04-19 19:25 被阅读0次

    与NSArray互转,下面方法只需将NSDictionary替换成NSArray

    1.JSON to NSDictionary

    - (NSDictionary *)dictionaryWithJson:(NSString *)jsonString {
        if (jsonString == nil) {
            return nil;
        }
        
        NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
        NSError *err;
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&err];
        if(err) {
            NSLog(@"json解析失败:%@",err);
            return nil;
        }
        return dic;
    }
    

    2.NSDictionary to JSON

    - (NSString*)jsonWithDictionary:(NSDictionary *)dic
    {
        NSString *jsonString = nil;
        if ([NSJSONSerialization isValidJSONObject:dic])
        {
            NSError *error;
            NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&error];
            jsonString =[[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
            if (error) {
                NSLog(@"Error:%@" , error);
            }
        }
        return jsonString;
    }
    

    相关文章

      网友评论

          本文标题:iOS Json和NSDictionary、NSArray 互转

          本文链接:https://www.haomeiwen.com/subject/bcwcgqtx.html