Stopped at NSJSONSERIALIZATION

Asked 2 years ago, Updated 2 years ago, 51 views

The URL listed in the source below stops at NSJSONSERIALIZATION.JSONObjectWithData every time.

I don't know the cause at all.
Other JSON URLs work fine.
What should I do?

let url=NSURL(string: "http://api.syosetu.com/novelapi/api/?out=json&lim=1")!
let task = NSURLSession.sharedSession().dataTaskWithURL(url,
    completionHandler: {data, response, error in
        iflet str=NSString(data:data!, encoding:NSUTF8StringEncoding){
            do{
                let dict = try NSJSONSERIALIZATION.JSONObjectWithData(data!,
                        options:NSJSONReadingOptions.AllowFragments) as!NSDictionary

            } catch{}
        }
})
task.resume()

swift json

2022-09-30 16:31

1 Answers

If you look at the JSONObjectWithData(_:options:) reference, you will see that the return value is AnyObject.The details are as follows:

Return Value
A Foundation object from the JSON data in data, oril if an error occurred.

NSJSONSERIALIZATION Class Reference

Returns Foundation objects depending on JSON.In practice,

  • If the root element is a dictionary, NSDictionary
  • If the root element is an array, NSArray

is returned.

We downcast from AnyObject to NSDictionary (basic to derivative type conversion, all Obj-C classes are treated as AnyObject derivatives).

Because downcasting is not secure, you must use either as! or as? as a runtime error if the types do not match.This is a runtime error because the former is utilized.

There are many ways to deal with it, but it's probably best to check the model.


2022-09-30 16:31

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.