【问题标题】:swift: diction list to jsonswift: 字典到 json
【发布时间】:2021-07-16 19:20:17
【问题描述】:

我如何将字典列表转换为 json?

struct User: Codable {
    var id = ""
    var deviceName = ""
}
    var userList:[Any] = []
    for user in users {
        var b : [String: Any] = [:]
        b["name"] = user.deviceName
        b["id"] = user.id
        //        b["uuid"] = user.uuid.uuidString
        userList.append(b)
        
    }
    print(JSONSerialization.isValidJSONObject(userList))
    
    do {
        let jsonData = try JSONSerialization.data(withJSONObject: userList, options: .prettyPrinted)
        return .ok(.json(jsonData))
    } catch {
        return .ok(.htmlBody("Error"))
    }

以 NSException 类型的未捕获异常终止 *** 由于未捕获的异常“NSInvalidArgumentException”而终止应用程序,原因:“JSON 写入中的类型无效 (__NSConcreteUUID)” 以 NSException 类型的未捕获异常终止

【问题讨论】:

  • 或者更好的是,使用Codable并直接使用JSONEncoder对用户进行编码。
  • 我是Codable的第一名,而且不擅长swift
  • User 是什么?
  • 我添加了User结构
  • 什么是“词典列表”?

标签: json swift dictionary


【解决方案1】:

您可以使用Codable 轻松编码和解码您的对象和 JSON:

do {
    let jsonEncoder = JSONEncoder()
    let jsonData = try jsonEncoder.encode(users)
    ,,,
} catch {
    print(error)
    return .ok(.htmlBody("\(error.localizedDescription)"))
}

一些旁注:

  1. 总是尝试打印出真正的error,而不是抛出一个简单的字符串。
  2. Catch 表示哪里有错误。因此,您可以考虑返回 badRequest 或其他内容,而不是 ok

您似乎需要传递一个 JSON。因此,您可以将 jsonData 转换为 jsonObject,例如:

    let jsonObject = try JSONSerialization.jsonObject(with: jsonData, options: [])
    print(JSONSerialization.isValidJSONObject(jsonObject)) // <- to verify
    return .ok(.json(jsonObject))

【讨论】:

  • 感谢您的回答,但是,print(JSONSerialization.isValidJSONObject(jsonData)) 是 FALSE
  • .json函数中,有JSONSerialization.isValidJSONObject
  • let jsonData = try jsonEncoder.encode(users) 返回空数据
  • 你确定users在传递给解码器之前不为空吗?我已经测试了代码并且它可以工作。请消除所有副作用并重新测试。
  • 如果可能的话,你能查一下stackoverflow.com/questions/68414125/with-swifter-json-response吗?
猜你喜欢
  • 1970-01-01
  • 2015-02-13
  • 2017-07-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多