首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >从JSON API追加到数组中

从JSON API追加到数组中
EN

Stack Overflow用户
提问于 2018-06-10 00:15:43
回答 1查看 510关注 0票数 0

如何使用JSON Model Class将其追加到数组中。下面是我的JSON API请求:https://developer.github.com/v3/search/

代码语言:javascript
复制
import Foundation

typealias GitDecode = [GitDecodeElement]

struct GitDecodeElement: Codable {
    let totalCount: Int
    let incompleteResults: Bool
    let items: [Item]

    enum CodingKeys: String, CodingKey {
        case totalCount = "total_count"
        case incompleteResults = "incomplete_results"
        case items
    }
}

struct Item: Codable {
    let id: Int
    let nodeID, name, fullName: String
    let owner: Owner
    let itemPrivate: Bool
    let htmlURL, description: String
    let fork: Bool
    let url, createdAt, updatedAt, pushedAt: String
    let homepage: String
    let size, stargazersCount, watchersCount: Int
    let language: String
    let forksCount, openIssuesCount: Int
    let masterBranch, defaultBranch: String
    let score: Double

    enum CodingKeys: String, CodingKey {
        case id
        case nodeID = "node_id"
        case name
        case fullName = "full_name"
        case owner
        case itemPrivate = "private"
        case htmlURL = "html_url"
        case description, fork, url
        case createdAt = "created_at"
        case updatedAt = "updated_at"
        case pushedAt = "pushed_at"
        case homepage, size
        case stargazersCount = "stargazers_count"
        case watchersCount = "watchers_count"
        case language
        case forksCount = "forks_count"
        case openIssuesCount = "open_issues_count"
        case masterBranch = "master_branch"
        case defaultBranch = "default_branch"
        case score
    }
}

struct Owner: Codable {
    let login: String
    let id: Int
    let nodeID, avatarURL, gravatarID, url: String
    let receivedEventsURL, type: String

    enum CodingKeys: String, CodingKey {
        case login, id
        case nodeID = "node_id"
        case avatarURL = "avatar_url"
        case gravatarID = "gravatar_id"
        case url
        case receivedEventsURL = "received_events_url"
        case type
    }
}

这里我有我的类模型,其中我说出了我想从响应中提取的内容:

代码语言:javascript
复制
import Foundation

struct Git: Codable{

    let totalCount: Int
    let items: GitItem

    init ( totalCount: Int,
           itemID: Int, itemDescription: String,
          ownerID: Int, ownerAvatarURL: String) {

        self.totalCount = totalCount
        self.items = GitItem(id: itemID, description: itemDescription, owner: GitOwner(id: ownerID, avatarURL: ownerAvatarURL))
    }
}

struct GitItem: Codable{
    let id: Int
    let description: String
    let owner: GitOwner
}

struct GitOwner: Codable {
    let id: Int
    let avatarURL: String
}

现在,当我试图将所有自定义属性追加到数组中时,因为itemIDitemDescriptionownerIDownerAvatarURL在不同的类中,所以我陷入了困境。

下面是我如何使用JSONDecoder从JSON中获取所有的那个属性:

代码语言:javascript
复制
import UIKit

class MainViewController: UIViewController {

    var gitRepositoriesArray = [Git]()

    override func viewDidLoad() {
        super.viewDidLoad()

    }

    // Download Git Repositories from API
    func parseGitRepositories(){

        let url = URL(string: "https://developer.github.com/v3/search/")
        URLSession.shared.dataTask(with: url!) { (data, response, error) in
            if error == nil{
                do{
                    let gitRepositoriesList = try JSONDecoder().decode(GitDecode.self, from: data!)
                    for eachRepo in gitRepositoriesList{

                        self.gitRepositoriesArray.append(Git(totalCount: eachRepo.totalCount,
                                                    itemID: <#T##Int#> , itemDescription: <#T##String#>, ownerID: <#T##Int#>, ownerAvatarURL: <#T##String#>))


                    }

                }catch{
                    print(error.localizedDescription)
                }
            }
        }.resume()
    }
}
EN

回答 1

Stack Overflow用户

发布于 2018-06-10 01:02:54

你的Git结构中有一些问题。我已经像这样更正了初始化器:

代码语言:javascript
复制
struct Git: Codable{

let totalCount: Int
var items = [GitItem]()

init(totalCount: Int, items: [Item]) {
    self.totalCount = totalCount

    for item in items {
        self.items.append(GitItem(id: item.id, description: item.description, owner: GitOwner(id: item.owner.id, avatarURL: item.owner.avatarURL)))
    }

}

因此,您的解析方法将相应地进行更改:

代码语言:javascript
复制
    // Download Git Repositories from API
func parseGitRepositories(){

    let url = URL(string: "https://api.github.com/search/repositories?q=tetris+language:assembly&sort=stars&order=desc")
    URLSession.shared.dataTask(with: url!) { (data, response, error) in
        if error == nil{
            do{
                let gitRepositoriesList = try JSONDecoder().decode(GitDecode.self, from: data!)
                for eachRepo in gitRepositoriesList{
                    self.gitRepositoriesArray.append(Git(totalCount: eachRepo.totalCount, items: eachRepo.items))
                }

            }catch{
                print(error.localizedDescription)
            }
        }
        }.resume()
}

还要注意将url更改为https://api.github.com/search/repositories?q=tetris+language:assembly&sort=stars&order=desc。您在代码中使用的当前url只是带有示例的html页面。它不会返回正确的json结果。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50776216

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档