首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用JSONDecoder解码PascalCase JSON

使用JSONDecoder解码PascalCase JSON
EN

Stack Overflow用户
提问于 2020-03-19 03:32:38
回答 1查看 325关注 0票数 1

我需要用大写的首字母(又称PascalCase或UppperCamelCase)来解码一个JSON,如下所示:

代码语言:javascript
复制
{
    "Title": "example",
    "Items": [
      "hello",
      "world"
    ]
}

所以我创建了一个符合Codable的模型

代码语言:javascript
复制
struct Model: Codable {
    let title: String
    let items: [String]
}

但是JSONDecoder会抛出一个错误,因为情况不同。

代码语言:javascript
复制
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))

我希望将模型的属性保留在camelCase中,但我不能更改JSON格式。

EN

回答 1

Stack Overflow用户

发布于 2020-03-19 03:32:38

我发现一个很好的解决方案是创建一个类似于基金会中提供的.convertFromSnakeCaseKeyDecodingStrategy

代码语言:javascript
复制
extension JSONDecoder.KeyDecodingStrategy {
    static var convertFromPascalCase: JSONDecoder.KeyDecodingStrategy {
        return .custom { keys -> CodingKey in
            // keys array is never empty
            let key = keys.last!
            // Do not change the key for an array
            guard key.intValue == nil else {
                return key
            }

            let codingKeyType = type(of: key)
            let newStringValue = key.stringValue.firstCharLowercased()

            return codingKeyType.init(stringValue: newStringValue)!
        }
    }
}

private extension String {
    func firstCharLowercased() -> String {
        prefix(1).lowercased() + dropFirst()
    }
}

它很容易使用,如下所示:

代码语言:javascript
复制
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromPascalCase
let model = try! decoder.decode(Model.self, from: json)

Gist上的完整示例

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60746366

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档