我正在尝试使用Swift 4解析来自CoinmarketCap 的一些 JSON 响应。JSONDecoder()但问题是来自 json 的响应正在根据用户输入而变化。例如,如果用户想要欧元的价格,输出如下:
[
{
"price_eur": "9022.9695444"
}
]
Run Code Online (Sandbox Code Playgroud)
但如果用户想要以英镑为单位的价格:
[
{
"price_gbp": "7906.8032145"
}
]
Run Code Online (Sandbox Code Playgroud)
所以问题是Decodable如果变量(json键)名称发生变化,我应该如何制作继承自的结构?
我有以下表示 JSON 的结构:
struct Todo: Codable {
let ID: Int?
let LAST_DT_ADD: String?
let LAST_ID:Int?
}
Run Code Online (Sandbox Code Playgroud)
当我以同样的方式使用解码时:
let decoder = JSONDecoder()
do {
let todo = try decoder.decode(Todo.self, from: responseData)
completionHandler(todo, nil)
} catch {
print("error trying to convert data to JSON")
print(error)
completionHandler(nil, error)
}
Run Code Online (Sandbox Code Playgroud)
它可以正确解码,但是当我有小写的 JSON 项目时(例如,我有ID, LAST_DT_ADDand ,而不是, and ),它不会解码对象。我需要做什么?如何支持大写和小写?LAST_IDidlast_dt_addlast_id
我正在使用Swift可解码协议来解析我的JSON响应:
{
"ScanCode":"4122001131",
"Name":"PINK",
"attributes":{
"type":"Product",
"url":""
},
"ScanId":"0000000kfbdMA"
}
Run Code Online (Sandbox Code Playgroud)
我遇到一个问题,有时我会用键“ Id”而不是“ ScanId”来获取ScanId值。有办法解决这个问题吗?
谢谢
如何为primitiveInt、Bool 等类型自定义 JSONDecoder 的行为?
这是问题所在:
类型不能依赖后端。例如:布尔可以是真/假或“真”/“假”(布尔可以用双引号括起来)
我们至少有 300 个 Codable 结构,其中平均有 15 个属性,编写解码逻辑很麻烦。此外,逻辑或多或少保持不变,因此代码变得重复
因此,我正在寻找一个解决方案,如果有一个Type mismatch原始类型应该能够处理它,如果没有,那么它应该被设置为nil提供该类型是可选的。
struct Bool1: Codable{
private var bool: Bool?
public init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
if let b = try? container.decode(Bool.self) {
self.bool = b
} else if let string = try? container.decode(String.self) {
if string.lowercased() == "true" {
self.bool = true
} else if string.lowercased() == "false" { …Run Code Online (Sandbox Code Playgroud) 官方文件说:
如果第二个参数(关联)为NULL,则现在使用json_decode()函数选项JSON_OBJECT_AS_ARRAY。以前,JSON_OBJECT_AS_ARRAY始终被忽略。
此代码(AFAIK)完成了此更改和条件:
<?php
$an_object = new StdClass();
$an_object->some_atrribute = "value 1";
$an_object->other_atrribute = "value 2";
//an object
print_r($an_object);
$encoded = json_encode($an_object);
//here (null is passed in the second parameter)
$output = json_decode($encoded,null,512);
//using 7.2 should be array, however it is an object
print_r($output);
//array
$output = json_decode($encoded,true);
print_r($output);
Run Code Online (Sandbox Code Playgroud)
但是,仅最后一次打印以数组形式打印。
我理解不对吗?
我正在尝试将Json数据解码到我的模型中。这是我的模特
struct Devices : Codable {
var id :String?
var description :String?
var status : Int?
Run Code Online (Sandbox Code Playgroud)
}
var heroes = Devices()
print(DeviceId)
let loginParam: [String: Any] = [
"id": DeviceId
]
let manager = Alamofire.SessionManager.default
manager.session.configuration.timeoutIntervalForRequest = 5
manager.request("http://13.13.13.004/website/api/Customer/DeviceControl", method: .post , parameters: loginParam, encoding: JSONEncoding.prettyPrinted)
.responseData { response in
let json = response.data
do{
let decoder = JSONDecoder()
//using the array to put values
heroes = try decoder.decode(Devices.self, from: json!)
}catch let err{
print(err)
}
Run Code Online (Sandbox Code Playgroud)
该代码不会进入catch块。但是,英雄价值观归零。什么时候 ?尝试使用NsDictionary 其给定结果。
在异步环境中,对所有请求使用一个JSONDecoder会更有效(如果多个线程正在等待锁定,可能会导致延迟),或者为每个新请求创建新的JSONDecoder会更有效吗?
Apple文档说JSONDecoder类是可重用的,但它们没有进一步详细说明.
https://developer.apple.com/documentation/foundation/jsondecoder
有没有办法告诉 JSONDecoder 将传入的小数转换为字符串?
public struct Transaction: Decodable
{
public let total: NSDecimalNumber?
enum CodingKeys: String, CodingKey {
case total = "AMOUNT"
}
public init(from decoder: Decoder) throws
{
let values = try decoder.container(keyedBy: CodingKeys.self)
let total = try values.decode(Decimal.self, forKey: .total)
self.total = NSDecimalNumber(decimal: total);
}
}
Run Code Online (Sandbox Code Playgroud)
考虑当 AMOUNT 类似于 397289527598234759823475455622342424358363514.42 时会发生什么
我想使用我拥有的代码,我会得到 nonConformingFloatDecodingStrategy 异常而无法从中恢复或失去精度。
围绕愚蠢的 swift Decimal 的斗争被记录在了所有的地方,特别是在这里:
我正在尝试加载本地JSON文件并使用符合Decodable协议的模型进行解析。
JSON文件:
[
{
"body": {},
"header": {
"returnCode": "200",
"returnMessage": "Successfully Received",
}
}
]
Run Code Online (Sandbox Code Playgroud)
响应消息模型:
struct ResponseMessage: Decodable {
struct header: Decodable {
let returnCode: String
let returnMessage: String
}
}
Run Code Online (Sandbox Code Playgroud)
模拟API的实现:
let url = Bundle.main.url(forResource: "MockJSONData", withExtension: "json")!
do {
let data = try Data(contentsOf: url)
let teams = try JSONDecoder().decode(ResponseMessage.self, from: data)
print(teams)
} catch {
print(error)
}
Run Code Online (Sandbox Code Playgroud)
但是响应消息为此返回空数据。
感谢您的帮助和建议!
谢谢
这是我的问题,当我收到一些 JSON 时,碰巧有些值与所需的类型不匹配。我并不介意,我只对类型正确时的值感兴趣。
例如,以下结构:
struct Foo : Decodable {
var bar : Int?
}
Run Code Online (Sandbox Code Playgroud)
我希望它匹配这些 JSON:
{ "bar" : 42 } => foo.bar == 42
{ "bar" : null } => foo.bar == nil
{ "bar" : "baz" } => foo.bar == nil
Run Code Online (Sandbox Code Playgroud)
事实上,我正在寻找一个 optional Int,所以每当它是一个整数时我想要它,但是当它null或其他东西我想要时nil。
不幸的是,我们的好人JSONDecoder在最后一种情况下引发了类型不匹配错误。
我知道一种手动方法:
struct Foo : Decodable {
var bar : Int?
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.bar = try? container.decode(Int.self, forKey: …Run Code Online (Sandbox Code Playgroud)