首页 文章

将JSON内容解析为数组(Swift3)

提问于
浏览
-1

我是JSON的新手,我正在尝试在变量中存储多个值 .

这里我有从我的网站获得的示例输出

2016-12-04 22:17:53.137949 API Demo[739:12497] [] nw_host_stats_add_src recv too small, received 24, expected 28
2016-12-04 22:17:53.142094 API Demo[739:12497] [] ____nwlog_simulate_crash_inner_block_invoke dlopen CrashReporterSupport failed
2016-12-04 22:17:53.142577 API Demo[739:12497] [] __nwlog_err_simulate_crash simulate crash failed "nw_socket_set_common_sockopts setsockopt SO_NOAPNFALLBK failed: [42] Protocol not available"
2016-12-04 22:17:53.145324 API Demo[739:12497] [] nw_socket_set_common_sockopts setsockopt SO_NOAPNFALLBK failed: [42] Protocol not available, dumping backtrace:
        [x86_64] libnetcore-856.20.4
    0   libsystem_network.dylib             0x00000001073a2682 __nw_create_backtrace_string + 123
    1   libnetwork.dylib                    0x000000010767f932 nw_socket_add_input_handler + 3100
    2   libnetwork.dylib                    0x000000010765d4f4 nw_endpoint_flow_attach_protocols + 3768
    3   libnetwork.dylib                    0x000000010765c511 nw_endpoint_flow_setup_socket + 563
    4   libnetwork.dylib                    0x000000010765b270 -[NWConcrete_nw_endpoint_flow startWithHandler:] + 2612
    5   libnetwork.dylib                    0x000000010767644d nw_endpoint_handler_path_change + 1261
    6   libnetwork.dylib                    0x0000000107675e7c nw_endpoint_handler_start + 570
    7   libnetwork.dylib                    0x000000010768dae5 nw_endpoint_resolver_start_next_child + 2240
    8   libdispatch.dylib                   0x000000010711f980 _dispatch_call_block_and_release + 12
    9   libdispatch.dylib                   0x00000001071490cd _dispatch_client_callout + 8
    10  libdispatch.dylib                   0x0000000107126e6b _dispatch_queue_serial_drain + 236
    11  libdispatch.dylib                   0x0000000107127b9f _dispatch_queue_invoke + 1073
    12  libdispatch.dylib                   0x000000010712a3b7 _dispatch_root_queue_drain + 720
    13  libdispatch.dylib                   0x000000010712a08b _dispatch_worker_thread3 + 123
    14  libsystem_pthread.dylib             0x00000001074f24de _pthread_wqthread + 1129
    15  libsystem_pthread.dylib             0x00000001074f0341 start_wqthread + 13
(
        {
        "_links" =         {
            about =             (
                                {
                    href = "http://dpfqatar.com/wp-json/wp/v2/types/post";
                }
            );
            author =             (
                                {
                    embeddable = 1;
                    href = "http://dpfqatar.com/wp-json/wp/v2/users/1";
                }
            );
            collection =             (
                                {
                    href = "http://dpfqatar.com/wp-json/wp/v2/posts";
                }
            );
            curies =             (
                                {
                    href = "https://api.w.org/{rel}";
                    name = wp;
                    templated = 1;
                }
            );
            replies =             (
                                {
                    embeddable = 1;
                    href = "http://dpfqatar.com/wp-json/wp/v2/comments?post=56";
                }
            );
            self =             (
                                {
                    href = "http://dpfqatar.com/wp-json/wp/v2/posts/56";
                }
            );
            "version-history" =             (
                                {
                    href = "http://dpfqatar.com/wp-json/wp/v2/posts/56/revisions";
                }
            );
            "wp:attachment" =             (
                                {
                    href = "http://dpfqatar.com/wp-json/wp/v2/media?parent=56";
                }
            );
            "wp:term" =             (
                                {
                    embeddable = 1;
                    href = "http://dpfqatar.com/wp-json/wp/v2/categories?post=56";
                    taxonomy = category;
                },
                                {
                    embeddable = 1;
                    href = "http://dpfqatar.com/wp-json/wp/v2/tags?post=56";
                    taxonomy = "post_tag";
                }
            );
        };
        author = 1;
        categories =         (
            3
        );
        "comment_status" = open;
        content =         {
            protected = 0;
            rendered = " A huge alligator snapping turtle got stuck in a blocked drain pipe in Houston, Texas. \n";
        };
        date = "2016-12-04T23:32:08";
        "date_gmt" = "2016-12-04T20:32:08";
        excerpt =         {
            protected = 0;
            rendered = " A huge alligator snapping turtle got stuck in a blocked drain pipe in Houston, Texas. \n";
        };
        "featured_media" = 0;
        format = standard;
        guid =         {
            rendered = "http://dpfqatar.com/?p=56";
        };
        id = 56;
        link = "http://dpfqatar.com/alligator-snapping-turtles-great-escape/";
        meta =         {
        };
        modified = "2016-12-04T23:32:29";
        "modified_gmt" = "2016-12-04T20:32:29";
        "ping_status" = open;
        slug = "alligator-snapping-turtles-great-escape";
        sticky = 0;
        tags =         (
        );
        title =         {
            rendered = "Alligator snapping turtle’s great escape";
        };
        type = post;
    },
        {
        "_links" =         {
            about =             (
                                {
                    href = "http://dpfqatar.com/wp-json/wp/v2/types/post";
                }
            );
            author =             (
                                {
                    embeddable = 1;
                    href = "http://dpfqatar.com/wp-json/wp/v2/users/1";
                }
            );
            collection =             (
                                {
                    href = "http://dpfqatar.com/wp-json/wp/v2/posts";
                }
            );
            curies =             (
                                {
                    href = "https://api.w.org/{rel}";
                    name = wp;
                    templated = 1;
                }
            );
            replies =             (
                                {
                    embeddable = 1;
                    href = "http://dpfqatar.com/wp-json/wp/v2/comments?post=54";
                }
            );
            self =             (
                                {
                    href = "http://dpfqatar.com/wp-json/wp/v2/posts/54";
                }
            );
            "version-history" =             (
                                {
                    href = "http://dpfqatar.com/wp-json/wp/v2/posts/54/revisions";
                }
            );
            "wp:attachment" =             (
                                {
                    href = "http://dpfqatar.com/wp-json/wp/v2/media?parent=54";
                }
            );
            "wp:term" =             (
                                {
                    embeddable = 1;
                    href = "http://dpfqatar.com/wp-json/wp/v2/categories?post=54";
                    taxonomy = category;
                },
                                {
                    embeddable = 1;
                    href = "http://dpfqatar.com/wp-json/wp/v2/tags?post=54";
                    taxonomy = "post_tag";
                }
            );
        };
        author = 1;
        categories =         (
            3
        );
        "comment_status" = open;
        content =         {
            protected = 0;
            rendered = " Now don\U2019t worry\U200a-\U200ait\U2019s not shrieked amidst some kind of panicked, cold sweat. I\U2019m not having nightmares about search engines, or even the prolonged suffering of Google+ (though someone surely should be). \n";
        };
        date = "2016-12-04T23:31:00";
        "date_gmt" = "2016-12-04T20:31:00";
        excerpt =         {
            protected = 0;
            rendered = " Now don\U2019t worry\U200a-\U200ait\U2019s not shrieked amidst some kind of panicked, cold sweat. I\U2019m not having nightmares about search engines, or even the prolonged suffering of Google+ (though someone surely should be). \n";
        };
        "featured_media" = 0;
        format = standard;
        guid =         {
            rendered = "http://dpfqatar.com/?p=54";
        };
        id = 54;
        link = "http://dpfqatar.com/okay-google-you-need-a-cuter-name/";
        meta =         {
        };
        modified = "2016-12-04T23:31:00";
        "modified_gmt" = "2016-12-04T20:31:00";
        "ping_status" = open;
        slug = "okay-google-you-need-a-cuter-name";
        sticky = 0;
        tags =         (
        );
        title =         {
            rendered = "Okay Google, you need a cuter name";
        };
        type = post;
    },
        {
        "_links" =         {
            about =             (
                                {
                    href = "http://dpfqatar.com/wp-json/wp/v2/types/post";
                }
            );
            author =             (
                                {
                    embeddable = 1;
                    href = "http://dpfqatar.com/wp-json/wp/v2/users/1";
                }
            );
            collection =             (
                                {
                    href = "http://dpfqatar.com/wp-json/wp/v2/posts";
                }
            );
            curies =             (
                                {
                    href = "https://api.w.org/{rel}";
                    name = wp;
                    templated = 1;
                }
            );
            replies =             (
                                {
                    embeddable = 1;
                    href = "http://dpfqatar.com/wp-json/wp/v2/comments?post=52";
                }
            );
            self =             (
                                {
                    href = "http://dpfqatar.com/wp-json/wp/v2/posts/52";
                }
            );
            "version-history" =             (
                                {
                    href = "http://dpfqatar.com/wp-json/wp/v2/posts/52/revisions";
                }
            );
            "wp:attachment" =             (
                                {
                    href = "http://dpfqatar.com/wp-json/wp/v2/media?parent=52";
                }
            );
            "wp:term" =             (
                                {
                    embeddable = 1;
                    href = "http://dpfqatar.com/wp-json/wp/v2/categories?post=52";
                    taxonomy = category;
                },
                                {
                    embeddable = 1;
                    href = "http://dpfqatar.com/wp-json/wp/v2/tags?post=52";
                    taxonomy = "post_tag";
                }
            );
        };
        author = 1;
        categories =         (
            7
        );
        "comment_status" = open;
        content =         {
            protected = 0;
            rendered = "Apple has acknowledged for the first time that it is investing in building a self-driving car. \n In a letter to US transport regulators, Apple said it was “excited about the potential of automated systems in many areas, including transportation” \n";
        };
        date = "2016-12-04T23:30:05";
        "date_gmt" = "2016-12-04T20:30:05";
        excerpt =         {
            protected = 0;
            rendered = " Apple has acknowledged for the first time that it is investing in building a self-driving car. In a letter to US transport regulators, Apple said it was “excited about the potential of automated systems in many areas, including transportation” \n";
        };
        "featured_media" = 0;
        format = standard;
        guid =         {
            rendered = "http://dpfqatar.com/?p=52";
        };
        id = 52;
        link = "http://dpfqatar.com/apple-reveals-self-driving-car-plans/";
        meta =         {
        };
        modified = "2016-12-04T23:30:05";
        "modified_gmt" = "2016-12-04T20:30:05";
        "ping_status" = open;
        slug = "apple-reveals-self-driving-car-plans";
        sticky = 0;
        tags =         (
        );
        title =         {
            rendered = "Apple reveals self-driving car plans";
        };
        type = post;
    }
)

这是我的代码:

let url = URL(string: "http://www.dpfqatar.com/wp-json/wp/v2/posts")!

    let task = URLSession.shared.dataTask(with: url) { (data, response, error) in

        if error != nil {

            print(error)

        } else {

            if let urlContent = data {

                do {

                let jsonResult = try JSONSerialization.jsonObject(with: urlContent, options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject

                    print(jsonResult)


                } catch {

                    print("JSON Processing Failed")

                }  }  }  }

    task.resume()

如何在此示例中同时打印 idtitle ?我尝试了很多方法,但没有任何方法可以帮助我 .

2 回答

  • -1

    Thanks 为了你所有的帮助,我在深度搜索后找到答案,

    for anItem in jsonResult as! [Dictionary<String, AnyObject>] {
    let postID = anItem["id"] as! Int
    Print(postID)}
    
  • 0

    它看起来像你有一个元素,一个元素,一个字典 .

    您可以从数据中提取 idtitle ,如下所示:

    if let arrayOfDicts = jsonResult as [[String: AnyObject]],
        let obj = arrayOfObjects.first,
        let id = obj["id"] as? String,
        let titleDict as obj["title"] as? [String: String],
        let title = titleDict["rendered"] {
      print("id = \(id), title = \(title)")
    } else {
      print("Error extracting data from JSON container object")
    }
    

    (请注意,我在SO编辑器中编写了该代码 . 它可能包含一两个小的语法错误 . 您需要自己清理它 . )

相关问题