{"id":22015881,"url":"https://github.com/pircate/cleanjson","last_synced_at":"2025-04-05T13:05:52.945Z","repository":{"id":46990101,"uuid":"131944343","full_name":"Pircate/CleanJSON","owner":"Pircate","description":"Swift JSON decoder for Codable","archived":false,"fork":false,"pushed_at":"2023-09-27T08:04:00.000Z","size":7449,"stargazers_count":293,"open_issues_count":10,"forks_count":41,"subscribers_count":9,"default_branch":"master","last_synced_at":"2025-03-29T12:04:45.490Z","etag":null,"topics":["carthage","codable","json","jsondecoder","swift"],"latest_commit_sha":null,"homepage":"","language":"Swift","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/Pircate.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2018-05-03T05:07:44.000Z","updated_at":"2025-03-15T03:27:44.000Z","dependencies_parsed_at":"2024-06-18T15:26:48.672Z","dependency_job_id":"2ef862f2-46f3-4061-b314-8f88f2ce07c3","html_url":"https://github.com/Pircate/CleanJSON","commit_stats":null,"previous_names":[],"tags_count":46,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Pircate%2FCleanJSON","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Pircate%2FCleanJSON/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Pircate%2FCleanJSON/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Pircate%2FCleanJSON/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/Pircate","download_url":"https://codeload.github.com/Pircate/CleanJSON/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247339155,"owners_count":20923014,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["carthage","codable","json","jsondecoder","swift"],"created_at":"2024-11-30T04:29:43.476Z","updated_at":"2025-04-05T13:05:52.924Z","avatar_url":"https://github.com/Pircate.png","language":"Swift","readme":"# CleanJSON\n\n[![build](https://github.com/Pircate/CleanJSON/workflows/build/badge.svg)](https://github.com/Pircate/CleanJSON/actions?query=workflow%3ASwift)\n[![Version](https://img.shields.io/cocoapods/v/CleanJSON.svg?style=flat)](https://cocoapods.org/pods/CleanJSON)\n[![Carthage compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage)\n[![SPM support](https://camo.githubusercontent.com/db4e680db88f755692b027d972041b38481bb65f92659e5484c41373d82b94a0/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f53504d2d737570706f727465642d4445354334332e7376673f7374796c653d666c6174)](https://swift.org/package-manager/)\n[![License](https://img.shields.io/cocoapods/l/CleanJSON.svg?style=flat)](https://cocoapods.org/pods/CleanJSON)\n[![Platform](https://img.shields.io/cocoapods/p/CleanJSON.svg?style=flat)](https://cocoapods.org/pods/CleanJSON)\n[![codebeat badge](https://codebeat.co/badges/4306b03d-6f8d-46c5-b30e-70ca9015d57f)](https://codebeat.co/projects/github-com-pircate-cleanjson-master)\n\n\n继承自 JSONDecoder，在标准库源码基础上做了改动，以解决 JSONDecoder 各种解析失败的问题，如键值不存在，值为 null，类型不一致。\n\n\u003e 只需将 JSONDecoder 替换成 CleanJSONDecoder。\n\n## Example\n\nTo run the example project, clone the repo, and run `pod install` from the Example directory first.\n\n## Requirements\n* iOS 9.0\n* Swift 5.2\n\n## Installation\n\nCleanJSON is available through [CocoaPods](https://cocoapods.org) or [Carthage](https://github.com/Carthage/Carthage). To install\nit, simply add the following line to your Podfile or Cartfile:\n\n#### Podfile\n\n```ruby\npod 'CleanJSON'\n```\n\n#### Cartfile\n\n```ruby\ngithub \"Pircate/CleanJSON\"\n```\n\n## Import\n\n```swift\nimport CleanJSON\n```\n\n## Usage\n\n### Normal\n\n```swift\nlet decoder = CleanJSONDecoder()\ntry decoder.decode(Model.self, from: data)\n\n// 支持直接解析符合 JSON 规范的字典和数组\ntry decoder.decode(Model.self, from: [\"key\": value])\n```\n\n### Enum\n\n对于枚举类型请遵循 `CaseDefaultable` 协议，如果解析失败会返回默认 case\n\n**Note: 枚举使用强类型解析，关联类型和数据类型不一致不会进行类型转换，会解析为默认 case**\n\n```swift\nenum Enum: Int, Codable, CaseDefaultable {\n    \n    case case1\n    case case2\n    case case3\n    \n    static var defaultCase: Enum {\n        return .case1\n    }\n}\n```\n\n### Customize decoding strategy\n\n可以通过 `valueNotFoundDecodingStrategy` 在值为 null 或类型不匹配的时候自定义解码，默认策略请看[这里](https://github.com/Pircate/CleanJSON/blob/master/CleanJSON/Classes/JSONAdapter.swift)\n\n```swift\nstruct CustomAdapter: JSONAdapter {\n    \n    // 由于 Swift 布尔类型不是非 0 即 true，所以默认没有提供类型转换。\n    // 如果想实现 Int 转 Bool 可以自定义解码。\n    func adapt(_ decoder: CleanDecoder) throws -\u003e Bool {\n        // 值为 null\n        if decoder.decodeNil() {\n            return false\n        }\n        \n        if let intValue = try decoder.decodeIfPresent(Int.self) {\n            // 类型不匹配，期望 Bool 类型，实际是 Int 类型\n            return intValue != 0\n        }\n        \n        return false\n    }\n    \n    // 为避免精度丢失所以没有提供浮点型转整型\n    // 可以通过下面适配器进行类型转换\n    func adapt(_ decoder: CleanDecoder) throws -\u003e Int {\n        guard let doubleValue = try decoder.decodeIfPresent(Double.self) else { return 0 }\n        \n        return Int(doubleValue)\n    }\n    \n    // 可选的 URL 类型解析失败的时候返回一个默认 url\n    func adaptIfPresent(_ decoder: CleanDecoder) throws -\u003e URL? {\n        return URL(string: \"https://google.com\")\n    }\n}\n\ndecoder.valueNotFoundDecodingStrategy = .custom(CustomAdapter())\n```\n\n可以通过 `JSONStringDecodingStrategy` 将 JSON 格式的字符串自动转成 `Codable` 对象或数组\n\n```swift\n// 包含这些 key 的 JSON 字符串转成对象\ndecoder.jsonStringDecodingStrategy = .containsKeys([])\n\n// 所有 JSON 字符串都转成对象\ndecoder.jsonStringDecodingStrategy = .all\n```\n\n为 `keyDecodingStrategy` 新增了一个自定义映射器，可以只映射指定 coding path 的 key \n\n```swift\ndecoder.keyDecodingStrategy = .mapper([\n    [\"snake_case\"]: \"snakeCase\",\n    [\"nested\", \"alpha\"]: \"a\"\n])\n```\n\n### For Moya\n\n使用 `Moya.Response` 自带的 [map](https://github.com/Moya/Moya/blob/master/Sources/Moya/Response.swift) 方法解析，传入 `CleanJSONDecoder`\n\n```swift\nprovider = MoyaProvider\u003cGitHub\u003e()\nprovider.request(.zen) { result in\n    switch result {\n    case let .success(response):\n        let decoder = CleanJSONDecoder()\n        let model = response.map(Model.self, using: decoder)\n    case let .failure(error):\n        // this means there was a network failure - either the request\n        // wasn't sent (connectivity), or no response was received (server\n        // timed out).  If the server responds with a 4xx or 5xx error, that\n        // will be sent as a \".success\"-ful response.\n    }\n}\n```\n\n### For RxMoya\n\n```swift\nprovider = MoyaProvider\u003cGitHub\u003e()\n\nlet decoder = CleanJSONDecoder()\nprovider.rx.request(.userProfile(\"ashfurrow\"))\n    .map(Model.self, using: decoder)\n    .subscribe { event in\n        switch event {\n        case let .success(model):\n            // do someting\n        case let .error(error):\n            print(error)\n        }\n    }\n```\n\n## Author\n\nPircate, swifter.dev@gmail.com\n\n## License\n\nCleanJSON is available under the MIT license. See the LICENSE file for more info.\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fpircate%2Fcleanjson","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fpircate%2Fcleanjson","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fpircate%2Fcleanjson/lists"}