由于字符周围的值无效,因此无法解码json

时间:2019-12-18 10:31:18

标签: json swift api decodable

这是我正在尝试使用Decodable协议解码的JSON。

我收到此错误消息:

  

Swift.DecodingError.dataCorrupted(Swift.DecodingError.Context(codingPath:[],debugDescription:“给定的数据不是有效的JSON。”,underlyingError:可选(错误域= NSCocoaErrorDomain代码= 3840,“字符周围的转义控制字符718。

let jsonData = """
{
    "pagination": {
        "per_page": 10,
        "previous_page": null,
        "total": 51,
        "next_page": 2,
        "current_page": 1
    },
    "collection": [
        {
            "id":408979,
            "asker_id":948560,
            "answer_id":"0c5e0296-6df8-47f0-8ebe-978cdfbaeb0d",
            "package_id":"00000000-0000-0000-0000-000000000000",
            "category_id":40,
            "address":"27 Boulevard Jean Rose, 77100 Meaux, France",
            "city":"Meaux",
            "created_at":"2019-12-16T11:25:44+01:00",
            "updated_at":"2019-12-16T11:25:44+01:00",
            "title":"voici le test de la demande",
            "description":"Titre : voici le test de la demande\nDescription : sdfghjhhhhhhhhhhhhhbvgnvh\nLocalisation : Meaux\nEst-ce pour une société ? : Non",
            "state":"open",
            "visibility":"public",
            "share_url":"https://dev.stoo.com/stoot/mission/voici-le-test-de-la-demande-408979",
            "shareUrl":"https://dev.stoo.com/stoot/mission/voici-le-test-de-la-demande-408979",
            "lat":"48.9616755",
            "lng":"2.8812038"
    }
]
}
""".data(using: .utf8)!

我检查了是否有键description,并且这是关联的值,这是问题的原因。

这是我的模特:

struct Results : Decodable {
    struct Pagination : Codable {
        let total: Int

        enum CodingKeys : String, CodingKey {
            case total
        }
    }

    struct Collection : Decodable {
        let id: Int
    }

    let pagination: Pagination
    let collection: [Collection]
} 

let model = try! JSONDecoder().decode(PagedCompanies.self, from: jsonData)

此响应来自API,无法对其进行更新。如何更新我的模型以正确解码json?

1 个答案:

答案 0 :(得分:1)

您可以自己快速找出位置718:

  • 替换

    let jsonData = """
    
    ...
    
    """.data(using: .utf8)!
    

    使用

    let jsonString = """
    
    ...
    
    """
    let jsonData = Data(jsonString.utf8)
    
  • 添加

    let startIndex = jsonString.index(jsonString.startIndex, offsetBy: 718)
    print(jsonString[startIndex...])
    

    并运行代码。

它立即显示受影响的字符是\n。在文字多行字符串语法中,任何反斜杠都必须使用第二个反斜杠转义

...
"description":"Titre : voici le test de la demande\\nDescription : sdfghjhhhhhhhhhhhhhbvgnvh\\nLocalisation : Meaux\\nEst-ce pour une société ? : Non"
...

如果数据来自服务器,则不会发生此错误。

结构正确。您甚至不需要total的CodingKeys。

相关问题