Skip to content

Commit 2f8ddda

Browse files
author
Sven
committed
feat: update README
1 parent 45cb776 commit 2f8ddda

File tree

1 file changed

+76
-1
lines changed

1 file changed

+76
-1
lines changed

README.md

Lines changed: 76 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,12 +2,87 @@
22

33
## 简介
44
OrderJSON 是手动解析 json 字符串, 使得字典 key 与 json key顺序一致。
5-
OrderJSON 并不是一个可以有顺序的字典。
5+
66

77
**背景**
88
在使用系统自带的 json 字符串转字典方法`JSONSerialization`后,发现字典是无序的。但是有时候我又想知道 key 的顺序。
99
所以在 [json -- swiftDo](https://github.com/swiftdo/json)基础上,使得我们可以获取 json 的 key 顺序。
1010

11+
## 使用
12+
13+
json 字符串
14+
``` javascript
15+
{
16+
"stringValue": "字符串",
17+
"intValue": 20,
18+
"doubleValue": 12.8,
19+
"boolValue": false,
20+
"objectValue": {
21+
"objectKey1": "value1",
22+
"objectKey2": 2,
23+
"objectKey3": {
24+
"key1": "value1",
25+
"key2""value2"
26+
}
27+
},
28+
"arrayValue1": [1, 2, 3],
29+
"arrayValue2": [{
30+
"name": "小明",
31+
"age": 18
32+
}],
33+
"emptyArray": [],
34+
"emptyObject": {},
35+
"nullValue": null
36+
}
37+
```
38+
### 装换为 OrderJSON
39+
40+
```swift
41+
let json =
42+
"""
43+
{"stringValue":"字符串","intValue":20,"doubleValue":12.8,"boolValue":false,"objectValue":{"objectKey1":"value1","objectKey2":2,"objectKey3":{"key":"value"}},"arrayValue1":[1,2,3],"arrayValue2":[{"name":"小明","age":18}],"emptyArray":[],"emptyObject":{},"nullValue":null}
44+
"""
45+
let jsonObject = try? JsonParser.parse(text: json)
46+
```
47+
### 获取根 key 顺序
48+
49+
转化路径为数组方法
50+
```swift
51+
private func transformStringToArray(_ string: String) -> [String] {
52+
if string.isEmpty {
53+
return []
54+
}
55+
return string.components(separatedBy: ".")
56+
}
57+
```
58+
通过路径数组,就可以获取对应 key 下子 key 的顺序数组
59+
```swift
60+
let rootPath = ""
61+
let rootKeys = jsonObject.subKeysFor(keyPath: transformStringToArray(rootPath))
62+
```
63+
输出结果
64+
```swift
65+
(lldb) po rootKeys
66+
10 elements
67+
- 0 : "stringValue"
68+
- 1 : "intValue"
69+
- 2 : "doubleValue"
70+
- 3 : "boolValue"
71+
- 4 : "objectValue"
72+
- 5 : "arrayValue1"
73+
- 6 : "arrayValue2"
74+
- 7 : "emptyArray"
75+
- 8 : "emptyObject"
76+
- 9 : "nullValue"
77+
```
78+
79+
多层 key 使用`.`连接
80+
比如`objectKey3`的子 key 顺序 ==》 path = "objectValue.objectKey3"
81+
```swift
82+
let multiPath = "objectValue.objectKey3"
83+
let multiPathPathKeys = jsonObject.subKeysFor(keyPath: transformStringToArray(multiPath)) // ["key1","key2"]
84+
```
85+
1186
参考文章
1287
- [Swift 码了个 JSON 解析器(一)](https://oldbird.run/swift/fp/t3-json1.html)
1388
- [Swift 码了个 JSON 解析器(二)](https://oldbird.run/swift/fp/t3-json2.html)

0 commit comments

Comments
 (0)