可解码和 JSON,同一变量有 2 种数据类型

2023-12-25

我正在使用 Decodable 协议来解码一些 json,但遇到了一个问题:

我得到了答案,其中如果没有向元素添加地理位置数据,则经度和纬度可以是整数 (latitude = 0),如果有地理数据,则可以是字符串 (fx.latitude = "25.047880")可用的。现在,当我解码 json 时,我不知道如何构建我的 Struct,因为 long 和 lat 不能同时是 String 和 Int。因此,在获取代表两种情况的元素时,我收到解码错误。

关于如何解决这个问题有什么建议吗?我尝试过使用“Any”作为数据类型,但这不符合 Decodable 协议

struct JPhoto: Decodable {
  let id: String
  let farm: Int
  let secret: String
  let server: String
  let owner: String
  let title: String
  let latitude: String //Can both be Int and String
  let longitude: String //Can both be Int and String
}

您需要编写自己的编码器/解码器。您可以使用关联的值枚举来执行此操作,使用 switch 语句进行编码并使用抛出/捕获行为进行解码:

enum AngularDistance:Codable {
    case string(String), integer(Int)

    func encode(to encoder: Encoder) throws {
        switch self {
        case .string(let str):
            var container = encoder.singleValueContainer()
            try container.encode(str)
        case .integer(let int):
            var container = encoder.singleValueContainer()
            try container.encode(int)
        }
    }

    init(from decoder: Decoder) throws {
        do {
            let container = try decoder.singleValueContainer()
            let str = try container.decode(String.self)
            self = AngularDistance.string(str)
        }
        catch {
              do { let container = try decoder.singleValueContainer()
                   let int = try container.decode(Int.self)
                   self = AngularDistance.integer(int) 
              }
              catch {
                   throw DecodingError.typeMismatch(AngularDistance.self, DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Expected to decode an Int or a String"))
              }
        }
    }
}

这是编码和解码的示例AngularDistance type:

let lat = [AngularDistance.string("String"), AngularDistance.integer(10)]
let encoder = JSONEncoder()
var decoder = JSONDecoder()

do {
    let encoded = try encoder.encode(lat)
    try decoder.decode(Array<AngularDistance>.self, from: encoded)
}
catch DecodingError.typeMismatch(let t, let e)  {
    t
    e.codingPath
    e.debugDescription
}
catch {
    print(error.localizedDescription)
    }

这是重写的结构:

struct JPhoto: Decodable {
  let id: String
  let farm: Int
  let secret: String
  let server: String
  let owner: String
  let title: String
  let latitude: AngularDistance //Can both be Int and String
  let longitude: AngularDistance //Can both be Int and String
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

可解码和 JSON,同一变量有 2 种数据类型 的相关文章

随机推荐

  • 正则表达式重用一个模式来捕获多个组?

    我想多次匹配某个模式 就像描述的那样here https stackoverflow com questions 41878948 is it possible to define a pattern and reuse it to cap
  • 为 NSTextField 设置边框

    哇 我真的掉进兔子洞了 我试图在 UI 部分的背景上添加文本 并将文本字段作为另一部分 例如生日在 然后我想重新调整该文本字段的用途以允许输入文本 所以我做了类似的事情 myTextFieldName editable true myTex
  • 在 Preact 和 typescript 中使用 Web 组件

    我在用着自定义元素 https developer mozilla org en US docs Web Web Components Using custom elements又称为网络组件Preact https preactjs co
  • 如何绘制堆叠和归一化直方图?

    我有一个将连续值映射到离散类别的数据集 我想显示一个直方图 其中连续值作为 x 类别作为 y 其中条形堆叠并标准化 例子 import numpy as np import pandas as pd import matplotlib im
  • 在 Azure 数据工厂查找中处理 >5000 行

    我有一个复制活动 它将表从 MySQL 复制到 Azure 表存储 这很好用 但是当我在 Azure 表上进行查找时 出现错误 数据太多 这是按照文档设计的 Lookup 活动最多可包含 5 000 行 最大大小为 2 MB 另外还提 到了
  • Android:将参数传递给选项卡

    在我的 Android 应用程序中 我使用以下代码来创建选项卡 mTabHost FragmentTabHost findViewById android R id tabhost mTabHost setup this getSuppor
  • 脸书状态栏

    有人知道如何在新 Facebook 中找到状态栏的好教程吗 底部的那个 看起来真的很酷 我以为它是用 ajax 或 jquery 编写的 但不确定 以下是一些可能对您有帮助的有用链接 插件 定位页脚 http plugins jquery
  • 计算向量中元素的所有成对差异[重复]

    这个问题在这里已经有答案了 我的问题与之前的帖子密切相关 计算 R 中向量内的所有成对差异 https stackoverflow com questions 24314878 compute all pairwise difference
  • Rails 3 应用程序中的 Sass 导入错误 - “未找到或无法读取要导入的文件:指南针”

    我有一个成功运行的 Rails 3 应用程序compass init rails using blueprint 我可以 import stylesheets 目录中的文件 但当我尝试时出现错误 import compass 现在该应用程序
  • 在 CORS spring security + webFlux 中启用通配符

    我在使用 spring webFlux 制作的项目中启用了 spring security CORS 我的问题是我们接受来自以下机构的请求 http 本地主机 4200 http localhost 4200 我怎样才能让 CORS 接受来
  • 如何启用 chromedriver 从 selenium webdriver 登录

    如何从 selenium webdriver 中启用 chromedriver 详细日志记录功能 我找到了合适的方法loggingTo and enableVerboseLogging但似乎无法正确使用它们 require chromedr
  • 我怎样才能用汇编语言(MIPS)做小于或等于的事情?

    我面前有 C 代码 我必须将其翻译成 MIPS 汇编语言 我并不是在寻找直接的答案 但我希望有人纠正我思考问题的方式 我面前的C代码是 x z lt y 我已经知道 x y 和 z 分别存储在寄存器中6 美元 7 美元 8 美元 问题是我无
  • 使用 ASP.NET MVC 4 从控制器调用另一个不同的视图

    我有一个带有提交按钮的视图 Index cshtml 单击提交按钮时 它会调用控制器 TestController cs 内的操作 Action01 因此在操作结束时 我想以自定义视图模型作为参数返回到调用者 Index cshtml 视图
  • 使用日期时间索引 pandas 更快地加载 csv

    我经常迭代存储在 csv 文件中的金融价格数据 当我完成与时间相关的所有分析时 就像使用 pandas 日期时间对象来子集和组织数据的可访问性一样 我的问题是 当我将文件读入计算机内存时 会打扰parse dates提供的参数顶部panda
  • 在树莓派上安装 libmp3lame 以使用 FFMPEG

    我在我的 RPi 2 上使用带有 python 3 2 的 moviepy 模块 它使用 FFMPEG 来读取和写入视频 所以我使用安装了 FFMPEGthese http hannes enjoys it blog 2016 03 ffm
  • 填充曲线和x轴之间的区域

    我试图使用 MatPlotLib 简单地填充 Python 中绘图曲线下的区域 这是我的 SSCCE import json import pprint import numpy as np import matplotlib pyplot
  • AngularJS 对包含 null 的列表进行排序

    我有一个范围对象 它有一个包含空值的列表 我想在两个方向上对该列表进行排序 但空值必须始终位于末尾 我可以很容易地做到这一点 方法是将对象分成 2 个 一个包含空值 一个不包含最后的空列表 但有没有更有效的方法来做到这一点呢 例子 1 nu
  • Nhibernate.Linq:使用Where(Expression>)限制查询结果

    我使用 NHibernate 查询数据库 现在我需要使用谓词限制选择的数据 到目前为止 我发现 Google 驱动的开发处于最佳状态 使用表达式和 NHibernate Linq 可以实现类似的功能 这是我尝试过的 public IList
  • VHDL乘法器

    library IEEE use IEEE STD LOGIC 1164 ALL entity Lab3 Adder1 is Port cin in STD LOGIC a in STD LOGIC VECTOR 3 downto 0 b
  • 可解码和 JSON,同一变量有 2 种数据类型

    我正在使用 Decodable 协议来解码一些 json 但遇到了一个问题 我得到了答案 其中如果没有向元素添加地理位置数据 则经度和纬度可以是整数 latitude 0 如果有地理数据 则可以是字符串 fx latitude 25 047