强制将所有属性键和swift类的值转换为小写

时间:2019-04-23 19:53:25

标签: swift encodable

我需要将所有键及其类的值转换为小写。例如,

class Person : Encodable {
    var firstName: String
    var lastName: String
     var city: String
}

 var person = Person(firstName: "David", lastName: "Gill", city: 
 "Toronto")
 let encoder = JSONEncoder()
 encoder.keyEncodingStrategy = .convertToLowerCase
 let encoded = try encoder.encode(person)
 print(String(decoding: encoded, as: UTF8.self))

convertToLowerCase是我在JSONEncoder.KeyEncodingStrategy扩展名中添加的一种用于将密钥转换为小写字母的方法。

它打印-{"city":"Toronto","firstname":"David","lastname":"Gill"}

我需要打印的是-{"city":"toronto","firstname":"david","lastname":"gill"}

有人可以在这里帮忙吗?

3 个答案:

答案 0 :(得分:2)

赞:

struct Person : Codable {
    var firstName: String
    var lastName: String
    var city: String
    enum CodingKeys : String, CodingKey {
        case firstName = "firstname"
        case lastName = "lastname"
        case city
    }
    func encode(to encoder: Encoder) throws {
        var con = encoder.container(keyedBy: CodingKeys.self)
        try! con.encode(self.firstName.lowercased(), forKey: .firstName)
        try! con.encode(self.lastName.lowercased(), forKey: .lastName)
        try! con.encode(self.city.lowercased(), forKey: .city)
    }
}

测试:

let person = Person(firstName: "David", lastName: "Gill", city:
    "Toronto")
let encoder = JSONEncoder()
let encoded = try encoder.encode(person)
print(String(decoding: encoded, as: UTF8.self))
// {"firstname":"david","lastname":"gill","city":"toronto"}

您可能可以合并.convertToLowerCase来保存一些工作。

答案 1 :(得分:0)

您可以先转换每个值:

var firstName = "David"
var lastName = "Gill"
var city = "Toronto"

var editedFirst = firstName.lowercased()
var editedLast = lastName.lowercased()
var editedCity = city.lowercased()

 var person = Person(firstName: editedFirst, lastName: editedLast, city: 
 editedCity)

 let encoder = JSONEncoder()
 encoder.keyEncodingStrategy = .convertToLowerCase
 let encoded = try encoder.encode(person)
 print(String(decoding: encoded, as: UTF8.self))

它不能让您一次性转换整个对象的属性,但可以将您的值与键一起转换。

关于您是否可以为类中的每个属性进行遍历的问题:如何将每个属性的LowerCased版本添加到类中?

类似的东西:

class Person : Encodable {
    var firstName: String
    var lastName: String
     var city: String

  let editedFirst = firstName.lowercased()
  let editedLast = lastName.lowercased()
  let editedCity = city.lowercased()
}

然后您可以在需要时访问该小写的值。

答案 2 :(得分:0)

这不是一个完美的答案,但是输入评论太长了。

但这是我会尝试的:

  1. 将您的对象转换为字典(带有类似https://stackoverflow.com/a/46049763/503527的东西)

  2. 将字典值映射为小写(这对于映射字典值https://stackoverflow.com/a/24219069/503527是一个很好的答案)

  3. 一旦有了映射的字典,就可以使用JSONencode,并且应该拥有所需的内容。