JSONEncoder方法func encode<T>(_ value: T) throws -> Data where T : Encodable是可以抛出的。
我想知道为什么它是可抛出的:如果要编码的值不符合Encodable,则不应通过编译器,因此在运行时不应发生错误。
我正在玩Swift 4 Codable,当我认为我已经掌握了它时,我从响应中解码了Weather键.
let jsonData = """
{"coord":{"lon":-113,"lat":35},
"weather":[{"id":800,"main":"Clear","description":"clear sky","icon":"01n"}],
"base":"stations",
"main":{"temp":291.15,"pressure":1022,"humidity":72,"temp_min":291.15,"temp_max":291.15},
"visibility":16093,"wind":{"speed":3.6,"deg":200},
"clouds":{"all":1},
"dt":1503294780,"sys":{"type":1,"id":321,"message":0.184,"country":"US","sunrise":1503320222,"sunset":1503367937},
"id":5308281,"name":"Paulden","cod":200}
"""
Run Code Online (Sandbox Code Playgroud)
Swift模型:
//Top Level Container
struct Response: Codable {
enum ResponseKeys: String, CodingKey {
case name
case code = "cod"
case main
case weather
}
//Nested Level Keys: Response > Weather
enum WeatherKeys: String, CodingKey {
case weather
}
//Nested Level Keys: Response > Main
enum MainKeys: String, CodingKey {
case temp
case pressure
case humidity
case tempMin = "temp_min"
case tempMax = "temp_max" …Run Code Online (Sandbox Code Playgroud) 假设我有一个类似下面的模型,它允许我构建一个Foo对象树.
struct Foo {
var kind : Kind
enum Kind {
case node([Foo])
case leaf
}
}
Run Code Online (Sandbox Code Playgroud)
我怎样才能制作这款Codable,专门用于case node([Foo])?
我无法b在子类中设置该属性。继承自的父类Codable似乎运行良好。
我觉得自己似乎缺少了一些显而易见的东西,但是我很难看到树木所用的木头。
下面是我的问题的一个操场例子。 b尽管设置为,仍保持0 10。传入的是子类,但可以设置父属性(很奇怪!)。
class Primary : Codable {
var a: Int = 0
}
class Secondary : Primary {
var b: Int = 0
}
let c = Secondary.self
func testRef<T: Codable>(_ t: T.Type) {
let json = "{\"a\":5, \"b\" : 10}".data(using: .ascii)!
let testCodable = try? JSONDecoder().decode(t.self, from: json)
print("a >> \((testCodable as! Primary).a)")
print("b >> \((testCodable as! Secondary).b)")
}
testRef(c)
Run Code Online (Sandbox Code Playgroud)
输出是:
a >> 5
b >> 0
Run Code Online (Sandbox Code Playgroud)
任何提示或指示将不胜感激。
当“地址”数组不为空时,它运行良好。但是当“地址”数组为空时它会失败。任何帮助将不胜感激。我有地址对象的结构。基本上“地址”是“地址”类型的对象数组,但是当地址为空时它会失败。
{
"success": "1",
"message": "You have succesfully verified your mobile no",
"details": {
"customer_id": 825,
"is_delivery_available": "0",
"is_registration_complete": "0",
"is_customer_verified": "0",
"customer_status": "0",
"cart_count": "0",
"name_type": "mr",
"firstname": "",
"lastname": "",
"full_name": "",
"pincode": "",
"profile_pic": "",
"mobile": "8583846677",
"email": "",
"address": [
],
"referral_code": ""
}
}
Run Code Online (Sandbox Code Playgroud)
以上是我试图在 Swift4 中使用 Codable 解码的 JSON。
import Foundation
struct Signup: Codable {
var success:String?
var message:String?
var details:Details?
private enum CodingKeys: String, CodingKey { case success, message, details }
init(from decoder: …Run Code Online (Sandbox Code Playgroud) 我有JSON结构为:
"periods": {
"2018-06-07": [
{
"firstName": "Test1",
"lastName": "Test1"
}
],
"2018-06-06": [
{
"firstName": "Test1",
"lastName": "Test1"
}
]
}
Run Code Online (Sandbox Code Playgroud)
我试图这样解析:
public struct Schedule: Codable {
public let periods: Periods
}
public struct Periods: Codable {
public let unknown: [Inner]
public struct Inner: Codable {
public let firstName: String
public let lastName: String
}
private struct CustomCodingKeys: CodingKey {
var stringValue: String
init?(stringValue: String) {
self.stringValue = stringValue
}
var intValue: Int?
init?(intValue: Int) {
return …Run Code Online (Sandbox Code Playgroud) 我开始重写应用程序,我想使用Swift 4 Codable协议自动将json字符串转换为Objects and Structs。
有时,特别是在编码开始时,我遇到了解码问题,因此我想打印这些错误(不使用调试器),以防某些Bean无法正确解码。
问题是这样的:
如您所见,在调试器中,“ decodingError”对象上同时存在两种:
我的问题是,代码中该元素的唯一属性是errorDescription,failureReason等,均为nil。
如何打印在调试器中正确显示的值?
private func createWeatherObjectWith(json: Data, x:Any.Type ,completion: @escaping (_ data: Any?, _ error: Error?) -> Void) {
do {
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
let weather = try decoder.decode(x.self, from: json)
return completion(weather, nil)
} catch let error {
print("Error creating current weather from JSON because: \(error.localizedDescription)")
return completion(nil, error)
}
}
Run Code Online (Sandbox Code Playgroud)
在这里,我编写上面的代码,通过传递类类型将Json字符串解码为类对象.但是它给出了以下错误
Cannot invoke 'decode' with an argument list of type '(Any.Type, from: Data)'
Run Code Online (Sandbox Code Playgroud) 目前,我正在通过JSON进行通讯的主应用程序上构建应用程序扩展。主题和数据位于JSON中,并通过Apple的可编码协议进行解析。我现在遇到的问题是使NSAttributedString可编码兼容。我知道它不是内置的,但我知道它可以转换为数据并返回到nsattributedstring。
将NSAttributedString强制转换为数据以便通过JSON共享。
if let attributedText = something.attributedText {
do {
let htmlData = try attributedText.data(from: NSRange(location: 0, length: attributedText.length), documentAttributes: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType])
let htmlString = String(data: htmlData, encoding: .utf8) ?? ""
} catch {
print(error)
}
}
Run Code Online (Sandbox Code Playgroud)
将html JSON字符串转换回NSAttributedString:
do {
return try NSAttributedString(data: self, options: [.documentType: NSAttributedString.DocumentType.html, .characterEncoding: String.Encoding.utf8.rawValue], documentAttributes: nil)
} catch {
print("error:", error)
return nil
}
Run Code Online (Sandbox Code Playgroud)
如何制作一个具有nsAttributedTitle属性的结构,该属性的类型为NSAttributedString,并使其与自定义编码器解码器兼容?
结构示例(无需考虑可编码合规性):
struct attributedTitle: Codable {
var title: NSAttributedString
enum CodingKeys: String, CodingKey {
case …Run Code Online (Sandbox Code Playgroud) 在Swift 5.1中,我想解码一个包含名为self的元素的JSON文档。这是一个HAL文档,因此我无法更改元素名称。
JSON就是这样;
{
"_embedded": {
"eventList": [
{
"id": 1,
"datetime": "2020-04-20T20:00:00",
"description": "...",
"_links": {
"self": {
"href": "http://.../events/1"
}
}
},
{
"id": 2,
"datetime": "2020-04-19T08:30:00",
"description": "...",
"_links": {
"self": {
"href": "http://.../events/2"
}
}
}
]
},
"_links": {
"self": {
"href": "http://.../events"
}
}
}
Run Code Online (Sandbox Code Playgroud)
我的域模型如下所示
struct JSonRootElement: Codable {
var _embedded: JsonEmbedded
}
struct JsonEmbedded: Codable {
var eventList: [JsonEvent]
}
struct JsonEvent: Codable {
var id: Int
var datetime: String
var description: …Run Code Online (Sandbox Code Playgroud)