首页 > 代码库 > jsonString转NSDictionary

jsonString转NSDictionary

NSData *webData = http://www.mamicode.com/[ @"{\"1\":
               {\"name\": \"Jerry\",\"age\": \"12\"},
              \"2\":
               {\"name\": \"Bob\",\"age\": \"16\"} }
" dataUsingEncoding:NSUTF8StringEncoding ]; NSError *error; NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:webData options:0 error:&error];

/*
NSJSONReadingMutableContainers = (1UL << 0),  //  创建可变的数组或字典来接收  0

NSJSONReadingMutableLeaves = (1UL << 1), // 指定在JSON对象可变字符串被创建为NSMutableString的实例 1
NSJSONReadingAllowFragments = (1UL << 2) //  指定解析器应该允许不属于的NSArray或NSDictionary中的实例顶层对象   2

*/
NSLog(@"JSON DIct: %@", jsonDict);
输出如下:

JSON DIct: {
     1 =     {
         age = 12;
         name = Jerry;
     };
     2 =     {
         age = 16;
         name = Bob;
     };
}
如果你的jsonString是下面格式的话:

[ {"id":5,"title":"销售员","number":2,"education":1,"money":1,"years":1,"companyname":"腾讯网络技术有限公司","company":1},

{
"id":13,"title":"程序员","number":2,"education":1,"money":1,"years":1,"companyname":"腾讯网络技术有限公司","company":1} ]

那调用[NSJSONSerialization JSONObjectWithData:webData options:0 error:&error]返回的就是NSArray, NSArray里面是2个NSDictionary。