GVKun编程网logo

Swift JsonEncoder 元素顺序(swift jsondecoder)

15

对于SwiftJsonEncoder元素顺序感兴趣的读者,本文将会是一篇不错的选择,我们将详细介绍swiftjsondecoder,并为您提供关于Codable:实现在swift中像js那样使用JSO

对于Swift JsonEncoder 元素顺序感兴趣的读者,本文将会是一篇不错的选择,我们将详细介绍swift jsondecoder,并为您提供关于Codable: 实现在 swift 中像 js 那样使用 JSON、HandyJSON:Swift语言JSON转Model工具库、ios – JSONDecoder和JSONEncoder类是线程安全的吗?、ios – Swift:使用Alamofire和SwiftyJSON处理JSON的有用信息。

本文目录一览:

Swift JsonEncoder 元素顺序(swift jsondecoder)

Swift JsonEncoder 元素顺序(swift jsondecoder)

如何解决Swift JsonEncoder 元素顺序?

我目前正在处理一个项目,遗憾的是提供的 API 一团糟。我正在按照 this 媒体文章中关于 Indeterminate Types with Codable in Swift 的第一个解决方案对具有多个嵌套类型的 Codable 进行编码。 所以,我使用枚举来允许我的 Codable Messages 中的不同类型大致如下:

struct CommandBase: encodable {
   let command: CommandType

   enum CodingKeys: String,CodingKey {
      let command = "c"
   }
}

enum CommandType: encodable {
   case someCommand(someContainer)
   case someOtherCommand(someOtherContainer)

   func encode(to encoder: Encoder) throws {
      var container = encoder.container(keyedBy: CodingKeys.self)
      switch self {
      case .someCommand(let someContainer):
         try container.encode("something",forkey: .name)
         try container.encode(someContainer,forKey: .container)
         try container.encode("etc",forKey: .etc)
      case .someOtherCommand(let someOtherContainer):
          // about the same as above case
      }

   }  

   enum CodingKeys: String,CodingKey {
      case name
      case container
      case etc
   }

}

问题是,正如我提到的,我必须使用的 API 一团糟,需要以正确的顺序处理 json。但出于某种原因,标准 JsonEncoder 总是将 .container 放在首位。

这是一个重构,早期版本使用了几种泛型类型,导致代码难以阅读,但符合顺序。

JsonEncoder 有一个 outputFormatting 属性,它使用像 .sortedKeys 这样的 OutputFormatting 类型来按字母顺序对键进行排序。但我不明白是否以及如何利用此属性对嵌套编码进行排序。

有没有人知道如何按照我的需要对编码的消息进行排序?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

Codable: 实现在 swift 中像 js 那样使用 JSON

Codable: 实现在 swift 中像 js 那样使用 JSON

Codable: 实现在 swift 中像 js 那样使用 JSON

官方文档,关于 Codable 实现:https://developer.apple.com/documentation/foundation/archives_and_serialization/encoding_and_decoding_custom_types

js 一样,iOS 11 之后,swift 也可以方便的使用 json 来传递数据了。

要想使用 json, 你操作的类需要实现 Codable 接口
Foundation 中的所有类都已经实现了 Cadable,所以如果你的实体中没有自定义的一些数据类型,都可以直接使用 JSON

js 一样,swift 中的 json 也有:

  • JSONEncoder 将数据转成 json 数据
  • JOSNDecoderjson 数据,转为可用的你需要的数据类型

看下面的 PlayGround 例子便知道如何使用了

由对象转字符串

import Foundation

struct Person: Codable {
    var name: String
    var age: Int
    var intro: String
}

let kyle = Person(name: "Kyle", age: 29, intro: "A web developer")
let tina = Person(name: "Tina", age: 26, intro: "A teacher for English")
let persons = [kyle, tina]

// Encode
let encoder = JSONEncoder()
encoder.outputFormatting = .prettyPrinted // setup formatter
let jsonData = try encoder.encode(persons)
print(String(data: jsonData, encoding: .utf8)!)


// Decode
let decoder = JSONDecoder()
// 注意 decode() 中的第一个参数
let people = try decoder.decode(Array<Person>.self, from: jsonData)
print(people[0].name)

输出如下:

[
  {
    "name" : "Kyle",
    "age" : 29,
    "intro" : "A web developer"
  },
  {
    "name" : "Tina",
    "age" : 26,
    "intro" : "A teacher for English"
  }
]
Kyle

由字符串转对象

import Foundation

struct Person: Codable {
    let name: String
    let age: Int
    let intro: String
}

let jsonString = """
[
    {
        "name": "Kyle",
        "age": 27,
        "intro": "A font-end enginer",
        "location": "Jinan"
    },
    {
        "name": "Tina",
        "age": 26,
        "intro": "A UI enginer",
        "location": "Jinan"
    }
]
"""

// 1. 先从字符串转为 Data
let jsonData = jsonString.data(using: .utf8)!

// 2. 再用 Data 转成对应的对象
let decoder = JSONDecoder()
let persons = try decoder.decode(Array<Person>.self, from: jsonData)

print(type(of: persons[0]))

cadable.png

对象名与 json 名不一致时

有些时候,对象声明中的变量名跟json中的键名不一致,如 nameEn 在 json 中需要为 json_en
只需要在对象声明中用 CodingKeys 声明要转成的字符串即可,如下:不需要转的就不需要写 = 后面的东西了

//
//  Person.swift
//  CustomisedViews
//
//  Created by Kyle on 2020/3/2.
//  Copyright © 2020 KyleBing. All rights reserved.
//

import Foundation

struct Person: Codable {
    var id: String
    var name: String
    var nameEn: String
    var nickName: String
    var perk: String
    var motto: String
    var health: String
    var sanity: String
    var hunger: String
    var version: String
    var pic: String
    
        enum CodingKeys: String, CodingKey {
        case nameEn = "name_en"
        case nickName = "nick_name"
        // 下面这些变量名不需要变,就只写 case 就可以了
        // 要把对象中的变量全部遍历出来,不然会出错
            case id
            case name
            case perk
            case motto
            case health
            case sanity
            case hunger
            case version
            case pic
        }
}

HandyJSON:Swift语言JSON转Model工具库

HandyJSON:Swift语言JSON转Model工具库

总结

以上是小编为你收集整理的HandyJSON:Swift语言JSON转Model工具库全部内容。

如果觉得小编网站内容还不错,欢迎将小编网站推荐给好友。

ios – JSONDecoder和JSONEncoder类是线程安全的吗?

ios – JSONDecoder和JSONEncoder类是线程安全的吗?

我找不到任何可能暗示任何方式的证据.

我现在每次创建新实例并使用自定义解码/编码选项进行配置,并想知道我是否可以创建单例并在每次需要时将其出售.

解决方法

从 JSONDecoder和 JSONEncoder的代码来看,它们似乎是线程安全的.

encode()和decode()都使用JSONSerialization(自iOS 7和macOS 10.9以来一直是线程安全的),两种方法都在局部变量中创建自己的私有解码/编码对象.据我所知,没有共享存储空间.

代码可以在这里找到:
https://github.com/apple/swift/blob/master/stdlib/public/SDK/Foundation/JSONEncoder.swift

ios – Swift:使用Alamofire和SwiftyJSON处理JSON

ios – Swift:使用Alamofire和SwiftyJSON处理JSON

这肯定会被问过几次,但我还没有找到正确的答案,尽管我一直很努力.

我使用Alamofire和SwiftyJSON,我的JSON数据看起来像这样:

{
  "528" : {
    "name" : "Name 1","id" : "528","product_id" : null,"visible" : "0","level" : "2"
  },"29" : {
    "name" : "Name 2","id" : "29","visible" : "1","level" : "1"
  },"173" : {
    "name" : "Name 3","id" : "173","143" : {
    "name" : "Name 4","id" : "143",

…使用此代码:

Alamofire.request(.GET,dataURL,parameters: nil,encoding: .JSON)

    .responseJSON { (request,response,jsonData,error) in

        let json = JSON(jsonData!) 

        println(json)

    }

…所以JSON一切都应该没问题

>我如何访问该数据?我的意思是我如何获得名称,ID,product_ids等
>我如何将该数据(名称)放入我的TableViewController?

解决方法

我在我的一个项目中使用了SwiftyJSON和Alamofire.这是我如何使用它.

>创建一个名为APIProtocol的协议.
>使用GET方法设置API类,该方法接受APIProtocol类型的委托.
>设置TableViewController以实现APIProtocol.
>从TableViewController调用API.get()

// Step 1
protocol APIProtocol {
  func didReceiveResult(results: JSON)
}

// Step 2
func get(path: String,parameters: [String: AnyObject]? = nil,delegate: APIProtocol? = nil){
  let url = "\(self.hostname)\(path)"
  NSLog("Preparing for GET request to: \(url)")

  Alamofire.request(.GET,url,parameters: parameters)
    .responseJSON { (req,res,json,error) in
      if(error != nil) {
        NSLog("GET Error: \(error)")
        println(res)
      }
      else {
        var json = JSON(json!)
        NSLog("GET Result: \(json)")

        // Call delegate if it was passed into the call
        if(delegate != nil) {
            delegate!.didReceiveResult(json)
        }
      }
    }
}

// Step 3
class ActivityViewController: UITableViewController,APIProtocol {
  var activityModelList: NSMutableArray = [] // This is the array that my tableView is using.

  ... 

  func didReceiveResult(result: JSON) {
    var activities: NSMutableArray = []

    NSLog("Activity.didReceiveResult: \(result)")

    for (index: String,activity: JSON) in result {

      var activityModel = ActivityModel(
        id: activity["id"].intValue,message: activity["message"].stringValue
      )

      activities.addobject(activityModel)
    }

    // Set our array of new models
    activityModelList = activities

    // Make sure we are on the main thread,and update the UI.
    dispatch_sync(dispatch_get_main_queue(),{
      self.refreshControl!.endRefreshing()
      self.tableView.reloadData()
    })
  }
}

// Step 4
override func viewDidLoad() {
  MyAPI.get("/activities",delegate: self)
}

关于Swift JsonEncoder 元素顺序swift jsondecoder的问题我们已经讲解完毕,感谢您的阅读,如果还想了解更多关于Codable: 实现在 swift 中像 js 那样使用 JSON、HandyJSON:Swift语言JSON转Model工具库、ios – JSONDecoder和JSONEncoder类是线程安全的吗?、ios – Swift:使用Alamofire和SwiftyJSON处理JSON等相关内容,可以在本站寻找。

本文标签: