Search code examples
swiftswift-playground

swift how to parse complex json?


enter image description here Here is my method for parsing JSON

var apiUrl = NSURL(string: "http://127.0.0.1/api.php")
var apiData = NSData.dataWithContentsOfURL(apiUrl, options: NSDataReadingOptions.DataReadingUncached, error: nil)

var apiJson = NSJSONSerialization.JSONObjectWithData(apiData, options: NSJSONReadingOptions.AllowFragments, error: nil)

http://127.0.0.1/api.php url returned data.

{
    "tit":"服务器",
    "loc":[
        {
            "_name":"北京",
            "evn":"funckEvent:"
        },{
            "_name":"英国",
            "evn":"funckEvent:"
        },{
            "_name":"日本",
            "evn":"funckEvent:"
        },{
            "_name":"发过",
            "evn":"funckEvent:"
        },{
            "_name":"中国",
            "evn":"funckEvent:"
        }
    ]
}

How to loop json arrays ? I would like to cycle to print the contents of the brackets{"_name":"中国","evn":"funckEvent:"}

var loc = apiJson.objectForKey("loc")


Solution

  • That code works perfectly fine for me (running a localhost server serving that exact JSON at 'json.html'); however, it failed to print until I specified the specific port (in my case, NSURL(string: "http://127.0.0.1:8000/json.html")). Have you tried explicitly specifying the port?

    Furthermore, it may be enlightening to actually catch the error returned by dataWithContentsofURL by declaring an NSError variable and passing it in, like so:

    var error: NSError?
    var apiData = NSData.dataWithContentsOfURL(apiUrl, options: NSDataReadingOptions.DataReadingUncached, error: &error)
    

    To loop over an element here, you'll need to cast it as an array:

    var loc = apiJson.objectForKey("loc") as [AnyObject]
    for i in loc {
        println(i["_name"])
    }
    

    This will print:

    北京
    英国
    日本
    发过
    中国