Decode JSON to NSArray or NSDictionary

前端 未结 5 1626
野的像风
野的像风 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:23

    That particular string will decode into an NSDictionary because the outermost thing is a JSON object which maps onto a NSDictionary for every JSON implementation I have ever seen. If you want to process an arbitrary string, you'll need to test what you get back

    NSError *jsonError;
    id parsedThing = [NSJSONSerialization JSONObjectWithData:data options:0 error:&jsonError];
    if (parsedThing == nil)
    {
        // error
    }
    else if ([parsedThing isKindOfClass: [NSArray class]])
    {
        // handle array, parsedThing can be cast as an NSArray safely
    }
    else
    {
        // handle dictionary, parsedThing can be cast as an NSDictionary
        // NB only dictionaries and arrays allowed as long as NSJSONReadingAllowFragments 
        // not specified in the options
    }
    

提交回复
热议问题