Wrappres' Studio.

JSON相关

字数统计: 206阅读时长: 1 min
2020/02/16 Share

JSON相关

JSON,是JavaScript Object Notation的缩写。

JSON基于两种结构:

  • 名字/值对集合:这种结构在其他编程语言里被实现为对象,字典,Hash表,结构体或关联数组
  • 有序值列表:这种结构在其他编程语言里被实现为数组,向量,列表或序列

解析JSON

1
2
3
let jsonData = jsonString.data(using: .utf8)!
let decoder = JSONDecoder()
let jsonModel = try! decoder.decode(H5Editor.self, from: jsonData)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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))
}
// JSONDecoder 的初始化
let decoder = __JSONDecoder(referencing: topLevel, options: self.options)
// 从顶层开始解析 JSON
guard let value = try decoder.unbox(topLevel, as: type) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: [], debugDescription: "The given data did not contain a top-level value."))
}

return value
}
CATALOG
  1. 1. JSON相关
    1. 1.1. 解析JSON