ios SWIFT -处理来自HTTP请求的阵列响应正文

omqzjyyz  于 2022-11-26  发布在  iOS
关注(0)|答案(1)|浏览(176)

我最近用Java创建了一个Android应用程序,它通过PHP脚本和MySQL检索列表数据。

[
{
    "chapter_id": 1,
    "chapter_title": "Chapter 1: Awakening\u300aTo Find True Love\u300b",
    "media": [
        {
            "media_id": "992ea9eee0824d7e95503fc57f7c72b3",
            "media_title": "Episode 1",
            "media_description": "This lecture, is the \u201copening chapter\u201d of the ten lecture series of Unit 1 \u300aLove Lets Children Fly\u300b\r\n\r\nThere are no parents who don\u2019t love their children, but if don\u2019t know how to love, love will become hurt. Through Lao Wang's true story, the speaker explained that \"only say love is not enough, we must also know how to love\" in order to avoid the recurrence of family tragedy.\r\n\r\nEveryone is eager to have a golden key to happiness and love, so that our most beloved children can fly happily in the sky of love. But the question is where is the \"golden key to happiness and love\"?\r\n\r\nThis lecture will share 3 true touching stories of \u201clove lets children fly\u201d. Although the 3 protagonists come from different countries, indeed their parents have successfully mastered the golden key of Appreciation True Love, which let these 3 protagonists flying high with their invisible wings in the broad sky to chase their dreams.\r\n",
            "media_url": "992ea9eee0824d7e95503fc57f7c72b3",
            "media_url_alt": "f512a57f574647a2b747bb9452c096b3",
            "media_thumbnail": "992ea9eee0824d7e95503fc57f7c72b3",
            "view_count": 250,
            "like_count": 11,
            "favourite_count": 9,
            "media_type": "video",
            "created_date": "2020-12-05"
        },
        {
            "media_id": "eb9827ebabdc492fb496760013817497",
            "media_title": "Episode 1 Q&A",
            "media_description": "What should I do if my child procrastinates?\r\nDidn't attend class seriously?\r\nChildren love to play games and mobile phones?\r\nChildren react very slowly and do things very slowly. How to guide him?\r\nWhat to do if you have trouble concentrating?\r\nHow to let children take the initiative to write homework?\r\nWhat to do if the child is rebellious?",
            "media_url": "eb9827ebabdc492fb496760013817497",
            "media_url_alt": "ae481f86325b4d1fa1ff92777dded1f6",
            "media_thumbnail": "eb9827ebabdc492fb496760013817497",
            "view_count": 90,
            "like_count": 3,
            "favourite_count": 3,
            "media_type": "video",
            "created_date": "2020-12-05"
        }
    ]
},
{
    "chapter_id": 2,
    "chapter_title": "Chapter 2: Detoxification\u300aUnderstanding  Complaint Education\u300b",
    "media": [
        {
            "media_id": "f9f45733714c47088b5216ce8a956726",
            "media_title": "Episode 1",
            "media_description": "After listening to the lecture, I agree that appreciation is good, and I agree that appreciation is right, but when I want to practice it, I will naturally fall back to my original form! Many beginners ask: Why does this happen? This lecture will explain why this phenomenon is so hard to do, but so good to hear!",
            "media_url": "f9f45733714c47088b5216ce8a956726",
            "media_url_alt": "013c1bc866ef480884f52cfb74b64aaa",
            "media_thumbnail": "f9f45733714c47088b5216ce8a956726",
            "view_count": 28,
            "like_count": 2,
            "favourite_count": 0,
            "media_type": "video",
            "created_date": "2022-03-15"
        },
        {
            "media_id": "2d95873e89d54f8098b58e7de4825a61",
            "media_title": "Episode 1 Q & A",
            "media_description": "I believe that many audience members have found that their children have a negative and passive mindset towards everything, no matter how their parents guide them, they are still negative and passive, so how should we parents love and appreciate our children to be proactive? Of course, many children's first reaction to difficulties is negative, so how can we as parents guide our children to have the ability to react positively? This consultation lecture will answer the above major questions and make it easier for you to guide your children to become proactive and positive minded.",
            "media_url": "2d95873e89d54f8098b58e7de4825a61",
            "media_url_alt": "5af313d423c648a0bb30a28db51e039d",
            "media_thumbnail": "2d95873e89d54f8098b58e7de4825a61",
            "view_count": 5,
            "like_count": 1,
            "favourite_count": 1,
            "media_type": "video",
            "created_date": "2022-03-15"
        }
    ]
}
]

我现在正在创建这个应用程序的iOS版本。我对Swift还很陌生,在如何将这些数据读入应用程序方面遇到了障碍。在Java应用程序中,有相应翻译的“章节列表”和“媒体”对象。
这是我目前为止在Swift中为这个过程编写的代码。我为章节和媒体创建了一些结构体,但我仍然不确定它如何适合处理响应。

struct Chapter: Codable {
    var chapter_id: String
    var chapter_title: String
    var media = [Media]()
    
    struct Media: Codable {
        var media_id: String
        var media_title: String
        var media_description: String
        var media_url: String
        var media_url_alt: String
        var media_thumbnail: String
        var view_count: Int
        var like_count: Int
        var favourite_count: Int
        var media_type: String
        var created_date: String
    }
 }

func retrieveVideoList(language: String) {
    let url = URL(string: baseURL + "retrieveVideoList.php")!
    
    var urlRequest = URLRequest(url: url)
    urlRequest.httpMethod = "POST"
    urlRequest.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
    urlRequest.httpBody = "language=\(language)".data(using: .utf8)
    
    // Perform HTTP Request
    let session = URLSession.shared
    let task = session.dataTask(with: urlRequest) { (data, response, error) in

        // Check for Error
        if let error = error {
            print("Error took place \(error.localizedDescription)")
            return
        }
        
        guard let data = data else { return }
                
        let decoder = JSONDecoder()
        
        DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
            do {
                let jsonData = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as! [Any]                    
                print(jsonData)
            } catch {
                print(error.localizedDescription)
            }
        }
    }
    task.resume()
}

这是print(jsonData)的输出。我注意到上面示例中的“media”已经变成如下所示的media。

[{
    "chapter_id" = 1;
    "chapter_title" = "Chapter 1: Awakening\U300aTo Find True Love\U300b";
    media =     (
                {
            "created_date" = "2020-12-05";
            "favourite_count" = 9;
            "like_count" = 11;
            "media_description" = "This lecture, is the \U201copening chapter\U201d of the ten lecture series of Unit 1 \U300aLove Lets Children Fly\U300b
\n
\nThere are no parents who don\U2019t love their children, but if don\U2019t know how to love, love will become hurt. Through Lao Wang's true story, the speaker explained that \"only say love is not enough, we must also know how to love\" in order to avoid the recurrence of family tragedy.
\n
\nEveryone is eager to have a golden key to happiness and love, so that our most beloved children can fly happily in the sky of love. But the question is where is the \"golden key to happiness and love\"?
\n
\nThis lecture will share 3 true touching stories of \U201clove lets children fly\U201d. Although the 3 protagonists come from different countries, indeed their parents have successfully mastered the golden key of Appreciation True Love, which let these 3 protagonists flying high with their invisible wings in the broad sky to chase their dreams.
\n";
            "media_id" = 992ea9eee0824d7e95503fc57f7c72b3;
            "media_thumbnail" = 992ea9eee0824d7e95503fc57f7c72b3;
            "media_title" = "Episode 1";
            "media_type" = video;
            "media_url" = 992ea9eee0824d7e95503fc57f7c72b3;
            "media_url_alt" = f512a57f574647a2b747bb9452c096b3;
            "view_count" = 250;
        },
                {
            "created_date" = "2020-12-05";
            "favourite_count" = 3;
            "like_count" = 3;
            "media_description" = "What should I do if my child procrastinates?
\nDidn't attend class seriously?
\nChildren love to play games and mobile phones?
\nChildren react very slowly and do things very slowly. How to guide him?
\nWhat to do if you have trouble concentrating?
\nHow to let children take the initiative to write homework?
\nWhat to do if the child is rebellious?";
            "media_id" = eb9827ebabdc492fb496760013817497;
            "media_thumbnail" = eb9827ebabdc492fb496760013817497;
            "media_title" = "Episode 1 Q&A";
            "media_type" = video;
            "media_url" = eb9827ebabdc492fb496760013817497;
            "media_url_alt" = ae481f86325b4d1fa1ff92777dded1f6;
            "view_count" = 90;
        }
    );
}, {
    "chapter_id" = 2;
    "chapter_title" = "Chapter 2: Detoxification\U300aUnderstanding  Complaint Education\U300b";
    media =     (
                {
            "created_date" = "2022-03-15";
            "favourite_count" = 0;
            "like_count" = 2;
            "media_description" = "After listening to the lecture, I agree that appreciation is good, and I agree that appreciation is right, but when I want to practice it, I will naturally fall back to my original form! Many beginners ask: Why does this happen? This lecture will explain why this phenomenon is so hard to do, but so good to hear!";
            "media_id" = f9f45733714c47088b5216ce8a956726;
            "media_thumbnail" = f9f45733714c47088b5216ce8a956726;
            "media_title" = "Episode 1";
            "media_type" = video;
            "media_url" = f9f45733714c47088b5216ce8a956726;
            "media_url_alt" = 013c1bc866ef480884f52cfb74b64aaa;
            "view_count" = 28;
        },
                {
            "created_date" = "2022-03-15";
            "favourite_count" = 1;
            "like_count" = 1;
            "media_description" = "I believe that many audience members have found that their children have a negative and passive mindset towards everything, no matter how their parents guide them, they are still negative and passive, so how should we parents love and appreciate our children to be proactive? Of course, many children's first reaction to difficulties is negative, so how can we as parents guide our children to have the ability to react positively? This consultation lecture will answer the above major questions and make it easier for you to guide your children to become proactive and positive minded.";
            "media_id" = 2d95873e89d54f8098b58e7de4825a61;
            "media_thumbnail" = 2d95873e89d54f8098b58e7de4825a61;
            "media_title" = "Episode 1 Q & A";
            "media_type" = video;
            "media_url" = 2d95873e89d54f8098b58e7de4825a61;
            "media_url_alt" = 5af313d423c648a0bb30a28db51e039d;
            "view_count" = 5;
        }
    );
}]

如果有人能指引我正确的方向,我会非常感激。谢谢。

okxuctiv

okxuctiv1#

替换

let decoder = JSONDecoder()
    
    DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
        do {
            let jsonData = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as! [Any]                    
            print(jsonData)
        } catch {
            print(error.localizedDescription)
        }
    }

do {
       let res = try JSONDecoder().decode([Chapter].self,data)
        print(res)
 }
 catch  {
    print(error)
 }

相关问题