Swift 4解码简单的根级json值

时间:2017-10-16 10:48:58

标签: swift swift4 codable

根据JSON标准RFC 7159,这是有效的json:

22

如何使用swift4可解码将其解码为Int?这不起作用

let twentyTwo = try? JSONDecoder().decode(Int.self, from: "22".data(using: .utf8)!)

2 个答案:

答案 0 :(得分:12)

适用于良好的“JSONSerialization.allowFragments 阅读选项。来自documentation

  

allowFragments

     

指定解析器应该允许不是NSArray或NSDictionary实例的顶级对象。

示例:

let json = "22".data(using: .utf8)!

if let value = (try? JSONSerialization.jsonObject(with: json, options: .allowFragments)) as? Int {
    print(value) // 22
}

但是,JSONDecoder没有这样的选项,也不接受顶级 不是数组或字典的对象。人们可以看到 decode()方法调用的source code JSONSerialization.jsonObject()没有任何选项:

open func decode<T : Decodable>(_ type: T.Type, from data: Data) throws -> T {
    let topLevel: Any
    do {
       topLevel = try JSONSerialization.jsonObject(with: data)
    } catch {
        throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: [], debugDescription: "The given data was not valid JSON.", underlyingError: error))
    }

    // ...

    return value
}

答案 1 :(得分:0)

在iOS 13.1+和macOS 10.15.1+中,Line # Hits Time Per Hit % Time Line Contents ============================================================== 1 def f0_4(a, ranges, n_pre_b): 2 1 6465309.0 6465309.0 39.8 a.sort() 3 1 3088.0 3088.0 0.0 blen = [x*len(a)//n_pre_b for x in range(n_pre_b)] 4 1 4661.0 4661.0 0.0 b1 = [a[i] for i in blen] 5 1 4.0 4.0 0.0 blen.append(len(a)) 6 1 1.0 1.0 0.0 b1.append(a[-1]) 7 1 1.0 1.0 0.0 res = [] 8 1000001 540421.0 0.5 3.3 for low, up in ranges: 9 1000000 1180737.0 1.2 7.3 low_pre_b_i = bisect.bisect_left(b1,low) 10 1000000 608838.0 0.6 3.7 lo = blen[low_pre_b_i-1] 11 1000000 490782.0 0.5 3.0 hi = blen[low_pre_b_i] 12 1000000 2064953.0 2.1 12.7 l = bisect.bisect_left(a, low, lo=lo, hi=hi) 13 1000000 1212568.0 1.2 7.5 high_pre_b_i = bisect.bisect_left(b1,up) 14 1000000 606433.0 0.6 3.7 lo = blen[high_pre_b_i-1] 15 1000000 492544.0 0.5 3.0 hi = blen[high_pre_b_i] 16 1000000 460683.0 0.5 2.8 if l > lo: 17 54 103.0 1.9 0.0 res.append(bisect.bisect_right(a, up, lo=l, hi=hi)-l) 18 else: 19 999946 2132459.0 2.1 13.1 res.append(bisect.bisect_right(a, up, lo=lo, hi=hi)-l) 20 21 1 1.0 1.0 0.0 return res 可以在根级别处理原始类型。

在马丁的回答下方的链接文章中查看最新评论(2019年10月)。