SWIFT Json检查对象标题是否存在

问题描述 投票:0回答:1

我的代码检查代码:“此数据”是否为空,如何检查代码本身是否存在。一些响应可能只给我一个带有时间戳的空JSON。因此var代码将不存在。

或者是否有更好的方法完全做到这一点?因为我的JSON是

“基于文本输入的变量”将导致可能不存在“代码”的“代码”,其中将包含“某些信息”或““]]

*Top of script:*

struct Variables: Decodable {
var code: String
    }

typealias DecoderX = [String: Variables]

先前的功能设置来自用户文本的输入,这些输入与数据库进行了交叉检查,因此只有在设置了UserDefault输入的情况下,才会调用GetInfo。

func GetInfo() {

let Input1 = UserDefaults.standard.string(forKey: “UserInput1”) ?? “”
let Input2 = UserDefaults.standard.string(forKey: “UserInput2”) ?? “”
let Input3 = UserDefaults.standard.string(forKey: “UserInput3”) ?? “”
print(“Input Check 1: \(Input1) \(Input2) \(Input3)”)

//URL INFO With API key hidden
let jsonTask = URLSession.shared.dataTask(with: requestURL) { data, response, error in if response == response
{
    if let data = data, let body = String(data: data, encoding: .utf8)
    {
        do
        {
        let json = try? decoder.decode(DeocderX.self, from: data); DispatchQueue.main.async
        {
            print(“Input Check 2: \(json![Input1]!.code) \(json![Input2]!.code) \(json![Input3]!.code)”)
            if json?[Input1]?.code != nil
            {
                print("Good Information 1")
            }
            else
            {
                print("Found Nothing 1")
            }

            if json?[Input2]?.code != nil
            {
                print("Good Information 2")
            }
            else
            {
                print("Found Nothing 2")
            }
            if json?[Input3]?.code != nil
            {
                print("Good Information 3")
            }
            else
            {
                print("Found Nothing 3")
            }    
    }
    //rest of code not applicable

我的代码检查代码:“此数据”是否为空,如何检查代码本身是否存在。一些响应可能只给我一个带有时间戳的空JSON。因此,var代码将不存在。 ...

json swift xcode parsing
1个回答
0
投票

您可以使用SwiftyJSON库。您可以在this link

© www.soinside.com 2019 - 2024. All rights reserved.