Decode JSON to NSArray or NSDictionary

前端 未结 5 1634
野的像风
野的像风 2020-11-29 09:51

I hope to decode the JSON data below:

{
    \"content\":
    [   
        {
            \"1\":\"a\",
            \"2\":\"b\",
            \"3\":\"c\",
               


        
5条回答
  •  悲哀的现实
    2020-11-29 10:06

    which iOS version are you using? in iOS 5 you have the NSJSONSerialization class to parse JSON data, if you need to target older iOSs or MAC OSX you should use third parties lib such as SBJSON. The string posted will be a NSDictionary with an array with one dictionary. The array will be accessible using the key @"content"

    In code:

    NSString * jsonString = @"blblblblblb";
    NSStringEncoding  encoding;
    NSData * jsonData = [jsonString dataUsingEncoding:encoding];
    NSError * error=nil;
    NSDictionary * parsedData = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&error];
    

    In SWIFT 2.0:

        let jsonString = "blblblblblb"
        let encoding = NSUTF8StringEncoding
        let jsonData = jsonString.dataUsingEncoding(encoding)
        guard let jData = jsonData else {return}
        do {
            let parsedData = try NSJSONSerialization.JSONObjectWithData(jData, options: [])
        } catch let error {
            print("json error: \(error)")
        }
    

    [UPDATE] The NSJSONSerialization class is also available for 10.7 my comment wasn't correct.

提交回复
热议问题