从URL在Swift 4中解析JsonObject

Maki代码

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

因此,例如,我有此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”,“名称”:null,“标题”:“白色电源块”,“ 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“},{”类型“:”创意“,”名称“:”创意“}]],”类别“:[{”类型“:”“,”名称“:”所有“},{”类型“:” BoxFront“,”名称“:” BoxFront“},{” type“:” BoxBack“,” name“:” BoxBack“},{” type“:” Components“,” name“:” Components“},{” type“:” Customized “,” name“:” Customized“},{” type“:” Play“,” name“:” Play“},{” type“:” Miscellaneous“,” name“:” Miscellaneous“},{” type “:”成熟”,“名称”:“成熟”},{“类型”:“ uncat”,“名称”:“未分类”}],“许可证过滤器”:[{“类型”:“”,“名称”:“任何“},{”类型“:”重用“,”名称“:”允许复制“},{”类型“:”商业“,”名称“:”允许商业使用“},{”类型“:”修改“ ,“ name”:“允许修改”}],“ datefilters”:[{“ value”:“ alltime”,“ name”:“ All Time”}},{“ value”:“ today”,“ name”:“今天“},{” value“:” twodays“,” name“:” Two Days“},{” value“:” last7“,” name“:” Last 7 Days“},{” value“:” last30 ”,“ name”:“最近30天”},{“ value”:“年”,“ name”:“最近365天”}],“过滤器”:[{“ name”:“许可证”,“列表名”: “ licensefilters”,“ type”:“ licensefilter”},{“ name”:“类别”,“ listname”:“类别”,“ type”:“ tag”},{“ name”:“图库”,“ listname “:”图库“,”类型“:”图库“}]}}类别”,“类型”:“标签”},{“名称”:“图库”,“列表名称”:“图库”,“类型”:“图库”}]}}类别”,“类型”:“标签”},{“名称”:“图库”,“列表名称”:“图库”,“类型”:“图库”}]}}

现在,我的第一个尝试是以解析首页的方式解析此链接:

    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)")
    }

但这不起作用,因为我现在了解这是因为这是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/

还有更多,但他们没有帮助我...

雷尼尔·梅里安

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

使用此代码

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()
}

使用方法

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

结果记录已打印

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;
    }; } ) ])

更新了修复“应用程序传输安全性已阻止明文”的错误

调整您的info.plist

在此处输入图片说明

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章