2

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

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"}

有人可以在这里帮忙吗?

4

3 回答 3

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以节省一些工作。

于 2019-04-23T21:08:11.487 回答
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))

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

至于你关于我们是否可以为类中的每个属性循环这个问题:如何将每个属性的小写版本添加到类中?

像这样的东西:

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

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

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

于 2019-04-23T20:22:20.920 回答
0

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

但这是我要尝试的:

  1. 将您的对象转换为字典(使用类似https://stackoverflow.com/a/46049763/503527的内容)

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

  3. 一旦你有了映射字典,JSONencode,你应该有你需要的。

于 2019-04-23T20:48:35.517 回答