How to use NSJSONSerialization

后端 未结 12 765
天涯浪人
天涯浪人 2020-11-22 08:38

I have a JSON string (from PHP\'s json_encode() that looks like this:

[{\"id\": \"1\", \"name\":\"Aaa\"}, {\"id\": \"2\", \"name\":\"Bbb\"}]
         


        
12条回答
  •  爱一瞬间的悲伤
    2020-11-22 09:08

    [{"id": "1", "name":"Aaa"}, {"id": "2", "name":"Bbb"}]
    

    In above JSON data, you are showing that we have an array contaning the number of dictionaries.

    You need to use this code for parsing it:

    NSError *e = nil;
    NSArray *JSONarray = [NSJSONSerialization JSONObjectWithData: data options: NSJSONReadingMutableContainers error: &e];
            for(int i=0;i<[JSONarray count];i++)
            {
                NSLog(@"%@",[[JSONarray objectAtIndex:i]objectForKey:@"id"]);
                 NSLog(@"%@",[[JSONarray objectAtIndex:i]objectForKey:@"name"]);
            }
    

    For swift 3/3+

       //Pass The response data & get the Array
        let jsonData = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! [AnyObject]
        print(jsonData)
        // considering we are going to get array of dictionary from url
    
        for  item  in jsonData {
            let dictInfo = item as! [String:AnyObject]
            print(dictInfo["id"])
            print(dictInfo["name"])
        }
    

提交回复
热议问题