从 URL 解析 Swift 4 中的 JsonObject

Mak*_*des 2 api json ios swift swift4

对我来说,这似乎是一项非常简单的任务,但即使经过大量研究和尝试,我也无法使其正常工作......

所以我有例如这个 URL,据我所知,这是一个 JSONObject 的 api?!

http://api.geekdo.com/api/images?ajax=1&gallery=all&nosession=1&objectid=127023&objecttype=thing&pageid=357&showcount=1&size=thumb&sort=recent

如果我在浏览器中打开此链接,则会得到以下结果:

{"images":[{"imageid":"1567153","imageurl_lg":"https://cf.geekdo-images.com/images/pic1567153_lg.jpg","name":null,"caption":"白色力量牌","numrecommend":"6","numcomments":"0","user":{"username":"manosdowns","avatar":"1","avatarfile":"avatar_id33829.jpg "},"imageurl":"https://cf.geekdo-images.com/6fCr14v025ZKYhXRMnbhYR16Ta8=/fit-in/200x150/pic1567153.jpg"}],"config":{"sorttypes":[{"type" :"hot","name":"Hot"},{"type":"recent","name":"Recent"}],"numitems":402,"endpage":402,"galleries":[ {“类型”:”all","name":"All"},{"type":"game","name":"Game"},{"type":"people","name":"People"},{" type":"creative","name":"Creative"}],"categories":[{"type":"","name":"All"},{"type":"BoxFront","name ":"BoxFront"},{"type":"BoxBack","name":"BoxBack"},{"type":"Components","name":"Components"},{"type":"自定义","name":"Customized"},{"type":"Play","name":"Play"},{"type":"Miscellaneous","name":"Miscellaneous"},{"type ":"Mature","name":"Mature"},{"type":"uncat","name":"Uncategorized"}],"licensefilters":[{"type":"","name":"Any "},{"type":"reuse","name":"允许复制"},{"type":"commercial","name":"允许商业使用"},{"type":"modify" ,"name":"允许修改"}],"datefilters":[{"value":"alltime","name":"All Time"},{"value":"today","name":"今天"},{"value":"twodays","name":"两天"},{"value":"last7","name":"Last 7 Days"},{"value":"last30","name":"Last 30 Days"},{"value":"year","name":"Last365 Days"}],"filters":[{"name":"Licenses"," listname":"licensefilters","type":"licensefilter"},{"name":"Category","listname":"categories","type":"tag"},{"name":"Gallery" ,"listname":"gallery","type":"gallery"}]}}Category","listname":"categories","type":"tag"},{"name":"Gallery","listname":"galleries","type":"gallery"}]}}Category","listname":"categories","type":"tag"},{"name":"Gallery","listname":"galleries","type":"gallery"}]}}

现在我的第一次尝试是像解析主页一样解析这个链接:

    guard let myURL = URL(string: link) else {                                                 >             print("Error: \(link) doesn't seem to be a valid URL")
        return
    }

    do {
        link = try String(contentsOf: myURL, encoding: .ascii)
    } catch let error {
        print("Error: \(error)")
    }
Run Code Online (Sandbox Code Playgroud)

但这不起作用,因为我现在明白这是因为这是 JSON 编码?!

我搜索了解析 JSON 并找到了一些关于编码和解码的解释,但我的问题是,在给出的所有示例中,解释都是从“拥有”JsonObject 的内容开始的。我的问题是我可以在浏览器中读取 URL 的内容,但我需要 Xcode 本身中的 URL 内容,所以我可以解析它?!

所以在我的具体情况下,我只需要“imageurl_lg”的内容

...如果我可以在 Xcode 中显示我可以在浏览器中看到的内容,我会知道该怎么做 - 但是如何将链接的内容放入 Xcode 中?

作为参考,我还阅读了以下说明,但无法将它们应用于我的示例... https://www.raywenderlich.com/172145/encoding-decoding-and-serialization-in-swift-4

https://grokswift.com/json-swift-4/

还有一些,但他们没有帮助我......

Rei*_*ian 6

您需要使用 URLSession 任务来执行此操作,之后您需要JSONSerialization在此示例中使用我返回一个字典,[String:Any]您可以将其转换为您需要的任何模型

使用此代码

func fetchData(completion: @escaping ([String:Any]?, Error?) -> Void) {
    let url = URL(string: "http://api.geekdo.com/api/images?ajax=1&gallery=all&nosession=1&objectid=127023&objecttype=thing&pageid=357&showcount=1&size=thumb&sort=recent")!

    let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
        guard let data = data else { return }
        do {
            if let array = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String:Any]{
                completion(array, nil)
            }
        } catch {
            print(error)
            completion(nil, error)
        }
    }
    task.resume()
}
Run Code Online (Sandbox Code Playgroud)

怎么用

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    fetchData { (dict, error) in
        debugPrint(dict)
    }
}
Run Code Online (Sandbox Code Playgroud)

结果日志打印

Optional(["config": {
    categories =     (
                {
            name = All;
            type = "";
        },
                {
            name = BoxFront;
            type = BoxFront;
        },
                {
            name = BoxBack;
            type = BoxBack;
        },
                {
            name = Components;
            type = Components;
        },
                {
            name = Customized;
            type = Customized;
        },
                {
            name = Play;
            type = Play;
        },
                {
            name = Miscellaneous;
            type = Miscellaneous;
        },
                {
            name = Mature;
            type = Mature;
        },
                {
            name = Uncategorized;
            type = uncat;
        }
    );
    datefilters =     (
                {
            name = "All Time";
            value = alltime;
        },
                {
            name = Today;
            value = today;
        },
                {
            name = "Two Days";
            value = twodays;
        },
                {
            name = "Last 7 Days";
            value = last7;
        },
                {
            name = "Last 30 Days";
            value = last30;
        },
                {
            name = "Last 365 Days";
            value = year;
        }
    );
    endpage = 402;
    filters =     (
                {
            listname = licensefilters;
            name = Licenses;
            type = licensefilter;
        },
                {
            listname = categories;
            name = Category;
            type = tag;
        },
                {
            listname = galleries;
            name = Gallery;
            type = gallery;
        }
    );
    galleries =     (
                {
            name = All;
            type = all;
        },
                {
            name = Game;
            type = game;
        },
                {
            name = People;
            type = people;
        },
                {
            name = Creative;
            type = creative;
        }
    );
    licensefilters =     (
                {
            name = Any;
            type = "";
        },
                {
            name = "Copying allowed";
            type = reuse;
        },
                {
            name = "Commercial use allowed";
            type = commercial;
        },
                {
            name = "Modification allowed";
            type = modify;
        }
    );
    numitems = 402;
    sorttypes =     (
                {
            name = Hot;
            type = hot;
        },
                {
            name = Recent;
            type = recent;
        }
    ); }, "images": <__NSSingleObjectArrayI 0x600000010710>( {
    caption = "White power tiles";
    imageid = 1567153;
    imageurl = "https://cf.geekdo-images.com/6fCr14v025ZKYhXRMnbhYR16Ta8=/fit-in/200x150/pic1567153.jpg";
    "imageurl_lg" = "https://cf.geekdo-images.com/images/pic1567153_lg.jpg";
    name = "<null>";
    numcomments = 0;
    numrecommend = 6;
    user =     {
        avatar = 1;
        avatarfile = "avatar_id33829.jpg";
        username = manosdowns;
    }; } ) ])
Run Code Online (Sandbox Code Playgroud)

更新修复“应用传输安全已阻止明文”错误

调整您的 info.plist

在此处输入图片说明