JSONDecoder unable to decode *value/fragment* types on *Mac*

狂风中的少年 提交于 2020-01-16 08:27:12

问题


Does anyone know of a way to configure the Mac version of JSONDecoder so that it is able to decode fragment/value types?


I am writing Swift code that needs to work on both Mac and iOS. I am using Decodable with JSONDecoder to try and parse some JSON. I have an enum thats Decodable as follows:

enum SomeEnum: Int, Decodable {
    case valueA = 0
    case valueB = 1
}

And to test the Decodable aspect of this I have this unit test...

func test_problem() {

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

    let result = try! JSONDecoder().decode(SomeEnum.self, from: jsonData)

    XCTAssertEqual(result, SomeEnum.valueA)
}

This succeeds when run against an iOS target. HOWEVER when run against "My Mac" (which is on Mojave) an error is thrown from the decode call as follows:

Thread 1: Fatal error: 'try!' expression unexpectedly raised an error: Swift.DecodingError.dataCorrupted(Swift.DecodingError.Context(codingPath: [], debugDescription: "The given data was not valid JSON.", underlyingError: Optional(Error Domain=NSCocoaErrorDomain Code=3840 "JSON text did not start with array or object and option to allow fragments not set." UserInfo={NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.})))

It seems that the iOS JSONDecoder is capable of decoding fragments/value types but the Mac version of JSONDecoder is not.


回答1:


In Mojave (as well as in iOS 12) and lower you can't.

The Mac JSONDecoder can decode fragments in Catalina 10.15.1 and higher



来源:https://stackoverflow.com/questions/59627000/jsondecoder-unable-to-decode-value-fragment-types-on-mac

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!