【问题标题】:Swift decoding string JSON failsSwift解码字符串JSON失败
【发布时间】:2019-01-05 11:48:06
【问题描述】:
struct APOD: Codable {
    let points: String
    let full_name: String
    let description: String
}

let decoder = JSONDecoder()
let product = try! decoder.decode(APOD.self, from: jsonData.data(using: .utf8)!)

print(product.full_name)

我有一个名为 jsonData 的字符串,来自:https://www.instagram.com/georgeanisimow/?__a=1。我格式化了文件并将其粘贴到项目中,只是为了有一些工作。

不幸的是它失败了这个错误代码:

“线程 1:致命错误:'try!'表情意外地升起了 错误:Swift.DecodingError.keyNotFound(编码键(字符串值: “点”,intValue:无),Swift.DecodingError.Context(codingPath:[], debugDescription:“没有与键关联的值 CodingKeys(stringValue: \"points\", intValue: nil) (\"points\").", 底层错误:nil))"

我正在尝试在 JSON 中打印“full_name”的值。

这是 JSON 的开始:

let jsonData ="""    
{  
   "logging_page_id":"profilePage_592027119",
   "show_suggested_profiles":false,
   "graphql":{  
      "user":{  
         "biography":"- Represented by AEFH Talent and CESD Modeling - I travel a lot -",
         "blocked_by_viewer":false,
         "country_block":false,
         "external_url":null,
         "external_url_linkshimmed":null,
         "edge_followed_by":{  
            "count":4571
         },
         "followed_by_viewer":true,
         "edge_follow":{  
            "count":741
         },
         "follows_viewer":true,
         "full_name":"George Anisimow"
      }
   }
}"""

【问题讨论】:

  • 错误很明显:JSON 的根对象中没有键 points。该链接不显示任何内容。
  • @vadian 抱歉,没有意识到,不管怎样,我已经将 JSON 粘贴到项目中,没有获取数据。
  • 请编辑问题并添加(开头的)JSON。
  • @vadian 刚刚这样做了
  • 在您在问题中添加的JSON 中包含points, full_name, description 键。

标签: ios json swift codable jsondecoder


【解决方案1】:

你会得到full_name这些结构(我只指定了相关的键)

struct Root: Decodable {
    let graphql : Graphql
}

struct Graphql: Decodable {
    let user : User
}

struct User: Decodable {
    let fullName : String
}

并解码数据

let data = Data(jsonData.utf8)
do {
    let decoder = JSONDecoder()
    decoder.keyDecodingStrategy = .convertFromSnakeCase
    let result = try decoder.decode(Root.self, from: data)
    let fullname = result.graphql.user.fullName
    print(fullname)

} catch { print(error) }

【讨论】:

    【解决方案2】:

    有很多方法可以做到这一点

    第一种方法:

    do {
        let responseData = Data(data.utf8)
        let decodeData = try JSONDecoder().decode(Controller.self, from: responseData)
    
        if (decodeData.ErrorCode! == "0") {
            //Success
        } else {
            //Failure
        }
    } catch let jsonErr {
        //Failure
    }
    

    第二种方法:

    do {
        if let responseData = response.data, let decodedData = try JSONSerialization.jsonObject(with: responseData, options: []) as? [[String: Any]] {
         print(decodedData)
        }
    } catch let error as NSError {
        print(error)
    }
    

    【讨论】:

      猜你喜欢
      • 2021-07-09
      • 2017-07-12
      • 2016-09-24
      • 1970-01-01
      • 1970-01-01
      • 2017-08-21
      • 1970-01-01
      • 2023-03-07
      • 2015-04-14
      相关资源
      最近更新 更多