码迷,mamicode.com
首页 > 移动开发 > 详细

iOS NSDictionary <--> NSString(JSON) in Objc

时间:2017-05-15 13:06:14      阅读:233      评论:0      收藏:0      [点我收藏+]

标签:lin   mat   line   with   sda   dict   ons   character   datawit   

 

 

 

NSDictionary --> NSString

+ (NSString*)stringINJSONFormatForObject:(id)obj
{
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:obj
                                                       options:0 // If that option is not set, the most compact possible JSON will be generated
                                                         error:nil];

    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    jsonString = [jsonString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];  //去除掉首尾的空白字符和换行字符

    return jsonString;
}

 

 

NSString --> NSDictionary

+ (NSDictionary *)dictForJSONString:(NSString *)str
{
    NSData *jsonData = [str dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                        options:NSJSONReadingMutableContainers
                                                          error:nil];
    return dic;
}

 

iOS NSDictionary <--> NSString(JSON) in Objc

标签:lin   mat   line   with   sda   dict   ons   character   datawit   

原文地址:http://www.cnblogs.com/ficow/p/6855754.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!