JSONDecoder无法解码* Mac *上的* value/fragment *类型 [英] JSONDecoder unable to decode *value/fragment* types on *Mac*

查看:204
本文介绍了JSONDecoder无法解码* Mac *上的* value/fragment *类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人知道配置>的 Mac 版本以使其能够decode片段/值类型的方法吗?

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

我正在编写需要在Mac和iOS上都可以使用的Swift代码.我正在将DecodableJSONDecoder结合使用,以尝试解析一些JSON.我有一个枚举Decodable如下:

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
}

要测试Decodable方面,我要进行此单元测试...

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

针对iOS目标运行时,此操作成功.但是,当在我的Mac"(位于Mojave上)上运行时,会从decode调用中引发错误,如下所示:

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:

线程1:致命错误:尝试!"表达式意外引发错误: Swift.DecodingError.dataCorrupted(Swift.DecodingError.Context(codingPath: [],debugDescription:给定的数据不是有效的JSON.", 底层错误:可选(错误域= NSCocoaErrorDomain代码= 3840 "JSON文本不是以数组或对象开头,并且选项允许 片段未设置." UserInfo = {NSDebugDescription = JSON文本未设置 从数组或对象开始,然后选择允许不设置片段的方式.})))

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.})))

似乎iOS JSONDecoder能够解码片段/值类型,但Mac版本的JSONDecoder不能.

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

推荐答案

在Mojave(以及iOS 12)中,您不能降低版本.

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

Mac JSONDecoder可以解码Catalina 10.15.1和更高版本中的片段

The Mac JSONDecoder can decode fragments in Catalina 10.15.1 and higher

这篇关于JSONDecoder无法解码* Mac *上的* value/fragment *类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆