【问题标题】:Converting response NSArray to Object array swift3将响应 NSArray 转换为对象数组 swift3
【发布时间】:2016-12-12 14:05:20
【问题描述】:

您好,我可以从服务器获取数组列表的响应。但我不知道如何在对象数组 [Feed] 中解析该响应并将其发送到完成处理程序上。我的代码如下:

class FeedsService {

    private var feedsEndPoint: String = "https://jsonplaceholder.typicode.com/posts"

    public func getFeeds(completion: ([Feed]) -> Void) {
        Alamofire.request(feedsEndPoint, method: .get)
            .validate(statusCode: 200..<300)
            .validate(contentType: ["application/json"])
            .responseJSON{ response in
                print("Response \(response.result.value)")

        }
    }
}

饲料模型如下:

class Feed {
    private var title: String
    private var body: String

    init(title:String, body: String) {
        self.title = title
        self.body = body
    }

    public func getTitle() -> String {
        return self.title
    }

    public func getBody() -> String {
        return self.body;
    }
}

我想将其解析为 Feed Array 并在完成回调时发送。 我正在使用 Alamofire 休息库从休息服务器加载数据。

【问题讨论】:

  • 没有看到您的数据集是什么样子,任何人都无法回答您的问题。 -1
  • 我不知道你投了反对票请检查这里的数据集jsonplaceholder.typicode.com/postsO.o

标签: arrays json swift alamofire


【解决方案1】:

你可以试试这个:

    class FeedsService {

    private var feedsEndPoint: String = "https://jsonplaceholder.typicode.com/posts"

    public func getFeeds(completion: @escaping ([Feed]) -> Void) {
        Alamofire.request(feedsEndPoint, method: .get)
            .validate(statusCode: 200..<300)
            .validate(contentType: ["application/json"])
            .responseJSON{ response in
                print("Response \(response.result.value)")
                var feeds = [Feed]()
                if let jsonArray = response.result.value as? [[String: Any]] {
                    for json in jsonArray {
                        if let feed = Feed(json: json) {
                            feeds.append(feed)
                        }
                    }
                    completion(feeds)
                } else {
                    // handle error
                }
        }
    }
}

另外,更新您的 Feed 类:

class Feed {
    private var title: String
    private var body: String

    init(title:String, body: String) {
        self.title = title
        self.body = body
    }

    init?(json: [String: Any]) {
        guard let title = json["title"] as? String,
            let body = json["body"] as? String else {
                return nil
        }
        self.title = title
        self.body = body
    }

    public func getTitle() -> String {
        return self.title
    }

    public func getBody() -> String {
        return self.body;
    }
}

只需将“标题”和“正文”更改为您的 json 响应中的适当键即可。

正如 El Tomato 指出 Feed init 不起作用,这是一个可以在操场上试用的测试代码:

let testFeedJson = ["title": "Test Title", "body" : "Test Body"]
if let testFeed = Feed(json: testFeedJson) {
    print(testFeed.getTitle())
    print(testFeed.getBody())
}

【讨论】:

  • 您没有初始化 Feed 以创建 Feed 实例。
  • 对不起,我不明白。 Feed 实例在这里创建:if let feed = Feed(json: json) {feeds.append(feed)}
  • 检查更新的答案(在底部),请在操场上尝试 Feed 课程。请在给我-1之前告诉我那里有什么问题。
  • 是的,请检查您的答案,感谢您的回复,您能否澄清此代码让 feeds = response.result.value 为! [Feed] print("Feeds count : (feeds.count)") 它确实编译并且计数返回正确
  • 我不确定let feeds = response.result.value as! [Feed] 是否会创建一个Feed 对象数组。服务器正在返回 [String:Any] 对象的数组。您必须遍历该数组并从 [String:Any] 对象创建 Feed 对象。你可以试试我在回答中建议的代码吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-09
  • 2019-03-28
  • 2022-12-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多