我正在使用 Swift 5.1,并且有一个深度嵌套的 json 文件,我只想访问 json 文件中的一些元素并忽略其余数据。例如,我只想要下面 json 字符串中数组中的“artistName”和“releaseDate”值。如果我使用嵌套的可解码结构,我不想需要声明每个键名称只是为了获取这两个值的数组。
\n\n\n{"feed":{"title":"Coming Soon","id":"https://rss.itunes.apple.com/api/v1/us/apple-music/coming-soon/all/10/explicit.json","author":{"name":"iTunes Store","uri":"http://wwww.apple.com/us/itunes/"},"links":[{"self":"https://rss.itunes.apple.com/api/v1/us/apple-music/coming-soon/all/10/explicit.json"},{"alternate":"https://itunes.apple.com/WebObjects/MZStore.woa/wa/viewRoom?fcId=1396220241\\u0026app=music"}],"copyright":"Copyright \xc2\xa9 2018 Apple Inc. All rights reserved.","country":"us","icon":"http://itunes.apple.com/favicon.ico","updated":"2019-12-04T01:48:22.000-08:00",\n\n "results":[{"artistName":"Stormzy","id":"1487951013","releaseDate":"2019-12-13","name":"Heavy Is The Head","kind":"album","copyright":"\xe2\x84\x97 2019 Hashtag Merky Music Limited under exclusive license to Atlantic Records UK, a division of Warner Music UK Limited.","artistId":"394865154","contentAdvisoryRating":"Explicit","artistUrl":"https://music.apple.com/us/artist/stormzy/394865154?app=music","artworkUrl100":"https://is5-ssl.mzstatic.com/image/thumb/Music123/v4/3c/a8/7c/3ca87c13-bffa-3ebd-eec6-68ea78ab556d/190295403003.jpg/200x200bb.png","genres":[{"genreId":"18","name":"Hip-Hop/Rap","url":"https://itunes.apple.com/us/genre/id18"},{"genreId":"34","name":"Music","url":"https://itunes.apple.com/us/genre/id34"}],"url":"https://music.apple.com/us/album/heavy-is-the-head/1487951013?app=music"},{"artistName":"Camila Cabello","id":"1487577356","releaseDate":"2019-12-06","name":"Romance","kind":"album","copyright":"\xe2\x84\x97 2019 Simco Ltd. under exclusive license to Epic Records, a division of Sony Music Entertainment","artistId":"935727853","contentAdvisoryRating":"Explicit","artistUrl":"https://music.apple.com/us/artist/camila-cabello/935727853?app=music","artworkUrl100":"https://is4-ssl.mzstatic.com/image/thumb/Music113/v4/fa/89/c7/fa89c706-fecc-2ece-cfc2-661c42807fbd/886448121220.jpg/200x200bb.png","genres":[{"genreId":"14","name":"Pop","url":"https://itunes.apple.com/us/genre/id14"},{"genreId":"34","name":"Music","url":"https://itunes.apple.com/us/genre/id34"}],"url":"https://music.apple.com/us/album/romance/1487577356?app=music"},{"artistName":"Harry Styles","id":"1485802965","releaseDate":"2019-12-13","name":"Fine Line","kind":"album","copyright":"\xe2\x84\x97 2019 Erskine Records Limited, under exclusive license to Columbia Records, a Division of Sony Music Entertainment","artistId":"471260289","artistUrl":"https://music.apple.com/us/artist/harry-styles/471260289?app=music","artworkUrl100":"https://is4-ssl.mzstatic.com/image/thumb/Music113/v4/72/89/85/728985d1-9484-7b71-1ea8-0f0654f7dc16/886448022213.jpg/200x200bb.png","genres":[{"genreId":"14","name":"Pop","url":"https://itunes.apple.com/us/genre/id14"},{"genreId":"34","name":"Music","url":"https://itunes.apple.com/us/genre/id34"}],"url":"https://music.apple.com/us/album/fine-line/1485802965?app=music"},{"artistName":"Grimes","id":"1487294744","releaseDate":"2020-02-21","name":"Miss Anthropocene","kind":"album","copyright":"\xe2\x84\x97 2020 4AD …Run Code Online (Sandbox Code Playgroud) 我需要用大写首字母(又名 PascalCase 或 UppperCamelCase)解码 JSON,如下所示:
{
"Title": "example",
"Items": [
"hello",
"world"
]
}
Run Code Online (Sandbox Code Playgroud)
所以我创建了一个符合以下条件的模型Codable:
struct Model: Codable {
let title: String
let items: [String]
}
Run Code Online (Sandbox Code Playgroud)
但JSONDecoder会引发错误,因为情况不同。
Swift.DecodingError.keyNotFound(CodingKeys(stringValue: "title", intValue: nil), Swift.DecodingError.Context(codingPath: [], debugDescription: "No value associated with key CodingKeys(stringValue: \"title\", intValue: nil) (\"title\").", underlyingError: nil))
Run Code Online (Sandbox Code Playgroud)
我想将模型的属性保留在驼峰命名法中,但我无法更改 JSON 格式。
如何解码不同 JSON 对象的数组,其中每个对象的相同属性告诉您使用什么类型来解码它:
let json =
"""
[
{
"@type": "FirstObject",
"number": 1
},
{
"@type": "SecondObject",
"name": "myName"
}
]
"""
Run Code Online (Sandbox Code Playgroud)
这是一些基于类似答案的代码,它大部分都可以实现,但失败了,因为它不知道 CodingKeys 的用途.data:
struct FirstObject: MyData {
var dataType: String
var number: Int
enum CodingKeys: String, CodingKey {
case dataType = "@type"
case number
}
}
struct SecondObject: MyData {
var dataType: String
var name: String
enum CodingKeys: String, CodingKey {
case dataType = "@type"
case name
}
}
struct SchemaObj: Decodable
{
var dataType: …Run Code Online (Sandbox Code Playgroud) 我需要您的帮助来实现自定义 JSON 解码。API返回的JSON为:
{
"zones": [
{
"name": "zoneA",
"blocks": [
// an array of objects of type ElementA
]
},
{
"name": "zoneB",
"blocks": [
// an array of objects of type ElementB
]
},
{
"name": "zoneC",
"blocks": [
// an array of objects of type ElementC
]
},
{
"name": "zoneD",
"blocks": [
// an array of objects of type ElementD
]
}
]
}
Run Code Online (Sandbox Code Playgroud)
我不想将此 JSON 解析为毫无意义的区域数组。我想为每种特定类型的块生成一个带有数组的模型,如下所示:
{
"zones": [
{
"name": "zoneA",
"blocks": [
// …Run Code Online (Sandbox Code Playgroud) 我正在重构一些我之前使用过第三方JSON解析器的项目,而且我遇到了一个愚蠢的网站,它将一个布尔值作为字符串返回.
这是JSON响应的相关片段:
{
"delay": "false",
/* a bunch of other keys*/
}
Run Code Online (Sandbox Code Playgroud)
我的Decoding结构如下所示:
struct MyJSONStruct: Decodable {
let delay: Bool
// the rest of the keys
}
Run Code Online (Sandbox Code Playgroud)
我如何将JSON响应中返回的字符串转换为Bool以匹配Swift 4中的结构?虽然这篇文章很有帮助,但我无法弄清楚如何将字符串响应转换为布尔值.
是否可以实现Encodable和Decodable属性UIColor
当我尝试添加Decodable扩展时,我收到错误
extension UIColor : Decodable {
public required init(from decoder: Decoder) throws {
self.init(red: 1, green: 1, blue: 1, alpha: 1)
}
}
Run Code Online (Sandbox Code Playgroud)
错误:ColorStuff.playground:98:21:错误:初始化程序要求'init(from :)'只能通过
required初始化程序在非最终类'UIColor'的定义中满足公共必需的init(来自解码器:解码器)抛出{
我错过了一些明显的东西吗?
我对Encodable扩展没有任何问题- 这似乎是一个Decodable问题.
错误消息告诉我,由于无法访问UIColor类定义,我无法执行此操作
因此,我尝试在操场上使用JSON Decodable从api端点获取数据。我已经按照步骤创建了该结构,并使其符合要求Decodable。
import Foundation
struct Weather: Decodable {
let latitude: String
let longitude: String
let timezone: String
let offset: Int
let currently : Currently
init(latitude: String,longitude: String,timezone: String,offset: Int,currently : Currently) {
self.latitude = latitude
self.longitude = longitude
self.timezone = timezone
self.offset = offset
self.currently = currently
}
enum CodingKeys: String, CodingKey {
case currently = "currently",latitude = "latitude",longitude = "longitude",timezone = "timezone", offset = "offset"
}
}
struct Currently: Decodable {
let time: Int
let summary: String …Run Code Online (Sandbox Code Playgroud) I have this json:
{ "stuff": [
{
"type":"car",
"object":{
"a":66,
"b":66,
"c":66 }},
{
"type":"house",
"object":{
"d":66,
"e":66,
"f":66 }},
{
"type":"car",
"object":{
"a":66,
"b":66,
"c":66 }}
]}
Run Code Online (Sandbox Code Playgroud)
As you can see for "car" and "house" there are different "object" structs, but both under the tag "object".
It would be ideal if one ended up with something like
struct StuffItem: Decodable {
let type: TheType
let car: Car
let house: House
}
Run Code Online (Sandbox Code Playgroud)
Is there some …
我有一个名为 ServiceHealthApi 的适配器类,它具有以下功能:
final class ServiceHealthApi {
let mockApi = "https://staging.myapp.com/health"
func getHealth() -> Single<ServiceHealthResponseModel> {
let url = URL(string: mockApi)
guard let validUrl = url else { return .never() }
var urlRequest = URLRequest(url: validUrl)
urlRequest.httpMethod = "GET"
let headers = [
"Content-Type" : "application/json; charset=utf-8"
]
urlRequest.allHTTPHeaderFields = headers
return URLSession.shared.rx.data(request: urlRequest)
.take(1)
.map {
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
return try JSONDecoder().decode(ServiceHealthResponseModel.self, from: $0) }
.asSingle()
}
}
struct HealthResponseModel: Decodable {
struct DataResponse: Decodable …Run Code Online (Sandbox Code Playgroud) 我有以下模型:
struct Response: Decodable {
let message: String
}
struct ErrorResponse: Decodable {
let errorMessage: String
}
enum APIError: Error {
case network(code: Int, description: String)
case decoding(description: String)
case api(description: String)
}
Run Code Online (Sandbox Code Playgroud)
我正在尝试使用以下流程获取 url 并解析 JSON 响应:
func fetch(url: URL) -> AnyPublisher<Response, APIError> {
URLSession.shared.dataTaskPublisher(for: URLRequest(url: url))
// #1 URLRequest fails, throw APIError.network
.mapError { .network(code: $0.code.rawValue, description: $0.localizedDescription) }
// #2 try to decode data as a `Response`
.tryMap { JSONDecoder().decode(Response.self, from: $0.data) }
// #3 if decoding …Run Code Online (Sandbox Code Playgroud)