从api返回的数据始终为nil?

时间:2019-11-11 20:05:10

标签: swift api httprequest urlsession

我正在从API检索数据。问题在于数据总是返回nil。 它是一个问题列表,通常为10。我编写的代码始终返回10个nil结果。我尝试使用具有相同结构的不同API尝试相同的代码,并且始终有效。

这是结构:

struct Questions: Codable{
    let question: String?
}

这是代码:

guard let url = URL(string: "http://adminsapi.somee.com/Api/Test/?id=1") else { return }
    URLSession.shared.dataTask(with: url) { (data, response, error) in
        guard let data = data else { return }
        do{
            let test = try? JSONDecoder().decode([Questions].self, from: data)
            for ask in test{
                print(ask.question)
            }
        }
    }.resume()

这是我得到的结果:

nil nil nil nil nil nil nil nil nil nil

这是邮递员从API返回的数据:

[
    {
        "AskName": "Urgenct of defecation"
    },
    {
        "AskName": "Mucous and streaked stools"
    },
    {
        "AskName": "vomiting"
    },
    {
        "AskName": "Fever"
    },
    {
        "AskName": "Tympany on percussion"
    },
    {
        "AskName": "Bowel sounds"
    },
    {
        "AskName": "shifting dullness"
    },
    {
        "AskName": "psoas and obturator sign"
    },
    {
        "AskName": "rebound tenderness"
    },
    {
        "AskName": "signs of shock"
    }
]

此外,当我尝试解析json并以一个字符串读取整个数据时,它完全可以正常工作。我不知道问题出在哪里。

2 个答案:

答案 0 :(得分:0)

已编辑。您的问题结构不正确。这是正确解析结果的有效操场代码。

import UIKit
import PlaygroundSupport

let data = """
[
    {
        "AskName": "Urgenct of defecation"
    },
    {
        "AskName": "Mucous and streaked stools"
    },
    {
        "AskName": "vomiting"
    },
    {
        "AskName": "Fever"
    },
    {
        "AskName": "Tympany on percussion"
    },
    {
        "AskName": "Bowel sounds"
    },
    {
        "AskName": "shifting dullness"
    },
    {
        "AskName": "psoas and obturator sign"
    },
    {
        "AskName": "rebound tenderness"
    },
    {
        "AskName": "signs of shock"
    }
]
""".data(using: .utf8)!

struct Questions: Codable{
    let AskName:String
}

do {
    try JSONDecoder().decode([Questions].self, from: data)
} catch {
    print(error)
}

您也可以将其定义为:

struct Questions: Codable {
    let question: String

    private enum CodingKeys: String, CodingKey {
        case question = "AskName"
    }
}

答案 1 :(得分:0)

您的Question实现是错误的。您需要告诉编译器,question变量需要使用AskName键进行解码。

struct Questions: Codable {
    let question: String?

    private enum CodingKeys: String, CodingKey {
        case question = "AskName"
    }
}