js json串解码_快速解码可能为字符串或双精度的json字段

js json串解码

Codable provides an elegant and declarative way of decoding a JSON in Swift. We just need to define a Type that matches the structure of the JSON.

Codable提供了一种在Swift中解码JSON的优雅且声明式的方式。 我们只需要定义一个与JSON结构匹配的Type。

Unfortunately, we don’t live in a perfect world so as an iOS Developer, you could need to decode a JSON with a field that doesn’t always have the same type.

不幸的是,我们生活在一个不完美的世界中,因此,作为iOS开发人员,您可能需要使用不总是具有相同类型的字段来解码JSON。

Something like this

像这样

{
"movies": [
{
"title": "Start Trek: Generations","vote": 6.6
},
{
"title": "Start Trek: First Contact","vote": "7.6"
}
]
}

As you can see the vote field sometimes contains a Double

如您所见, vote字段有时包含一个Double

"vote": 6.6

and sometimes a String.

有时是String

"vote": "7.6"

This is an error from who is providing the JSON but sometimes you just need to deal with it. So here’s a quick solution to solve this problem using Codable.

这是谁提供JSON的错误,但有时您只需要处理它即可。 因此,这里是使用Codable解决此问题的快速解决方案。

电影结构 (The Movies struct)

First of all, let’s define a Swift struct to match the JSON structure.

首先,让我们定义一个Swift结构以匹配JSON结构。

struct Movies: Decodable {    let movies: [Movie]
struct Movie: Decodable {
let title: Stringlet vote: 🤔🤔🤔
}
}

Good, now we need to figure out which type to use for the vote field!

好,现在我们需要弄清楚vote字段要使用哪种类型!

Since we know that it could contain a String or a Double we can define an Enum for that.

因为我们知道它可以包含一个String或一个Double我们可以为此定义一个Enum。

StringOrDouble枚举 (The StringOrDouble Enum)

Here’s the core idea of this article. This enum is a Decodable Type that can match a string or a double found in the JSON.

这是本文的核心思想。 此枚举是可Decodable类型,可以匹配JSON中的stringdouble Decodable型。

enum StringOrDouble: Decodable {
case string(String)
case double(Double)
init(from decoder: Decoder) throws {
if let double = try? decoder.singleValueContainer().decode(Double.self) {
self = .double(double)
return
} if let string = try? decoder.singleValueContainer().decode(String.self) {
self = .string(string)
return
} throw Error.couldNotFindStringOrInt
} enum Error: Swift.Error {
case couldNotFindStringOrInt
}
}

它是如何工作的? (How does it work?)

The Enum defines 2 cases each one with an associated value.

枚举定义2个案例,每个案例都有一个关联的值。

The string case will contain a String value. And the double case will contain… well a Double.

string大小写将包含一个String值。 并且double大小写将包含…… Double

case string(String)
case double(Double)

Next, we provide a custom init which reads the value from the JSON and try to convert it first into a Double.

接下来,我们提供一个自定义的init ,它从JSON读取值,然后尝试首先将其转换为Double

If the conversion succeeds then we get a value of type StringOrDouble.double where the associated value if the number found in the JSON.

如果转换成功,那么我们将获得StringOrDouble.double类型的值,如果在JSON中找到该数字, StringOrDouble.double关联值。

If the conversion fails then we try to read a String to produce a value of type StringOrDouble.string.

如果转换失败,则我们尝试读取String以产生类型为StringOrDouble.string的值。

If also the second conversion fails then an error is thrown.

如果第二次转换也失败,那么将引发错误。

返回电影模式 (Back to the Movies model)

Now we can complete the implementation of the Movies model

现在我们可以完成Movies模型的实现

struct Movies: Decodable {    let movies: [Movie]
struct Movie: Decodable {
let title: String
let vote: StringOrDouble
}
}

测试中 (Testing)

Finally, we can decode our JSON.

最后,我们可以解码JSON。

let data = """
{
"movies": [
{
"title": "Start Trek: Generations",
"vote": 6.6
},
{
"title": "Start Trek: First Contact",
"vote": "7.6"
}
]
}
""".data(using: .utf8)!do {
let movies = try JSONDecoder().decode(Movies.self, from: data)
print(movies)
} catch {
print(error)
}

Result

结果

Movies(movies: [
Movies.Movie(title: "Start Trek: Generations",
vote: StringOrDouble.double(6.6)),
Movies.Movie(title: "Start Trek: First Contact",
vote: StringOrDouble.string("7.6"))
])

翻译自: https://medium.com/swlh/decoding-a-json-field-that-could-be-string-or-double-with-swift-f6ea6a2babf8

js json串解码

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值