Skip to content

Commit

Permalink
优化key的自定义映射规则
Browse files Browse the repository at this point in the history
  • Loading branch information
Mccc committed Oct 14, 2024
1 parent 0b6f0a5 commit 26a667a
Show file tree
Hide file tree
Showing 5 changed files with 92 additions and 100 deletions.
63 changes: 35 additions & 28 deletions Example/SmartCodable/Test2ViewController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -17,42 +17,49 @@ class Test2ViewController: BaseViewController {
super.viewDidLoad()

let dict: [String: Any] = [
"name": "mccc",
"subModel": "mccc111",
// "name": "mccc",
"age": 30,
"info": [
"name": "mccc111"
],
"sub": [
"subname": "qilin",
"subage": 3,
"info": [
"name": "qilin111"
],
]

]
let model = Model.deserialize(from: dict)
print(model?.subModel?.rawValue)

let dict1 = model?.toDictionary()
print(dict1)
BTPrint.print(model)

}

struct Model: SmartCodable {
var name: String = ""
@SmartPublished
var subModel: TestEnum?
print("\n")


static func mappingForValue() -> [SmartValueTransformer]? {
[
CodingKeys.name <--- FastTransformer<String, String>(fromJSON: { json in
"abc"
}),
CodingKeys.subModel <--- FastTransformer<TestEnum, String>(fromJSON: { json in
TestEnum.man
}),
]
}
let tranDict = model?.toDictionary() ?? [:]
BTPrint.print(tranDict)
}
}

struct Model: SmartCodable {
var name: String = ""
var age: Int = 0
var sub: SubModel = SubModel()

enum TestEnum: String, SmartCaseDefaultable {
case man
static func mappingForKey() -> [SmartKeyTransformer]? {
[
CodingKeys.name <--- "info.name"
]
}
}

struct SubModel: SmartCodable {
var subname: String = ""
var subage: Int = 0

struct SubModel: SmartCodable {
var name: String = ""

static func mappingForKey() -> [SmartKeyTransformer]? {
[
CodingKeys.subname <--- "info.name"
]
}
}
74 changes: 20 additions & 54 deletions Example/SmartCodable/Test3ViewController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import CleanJSON
/** 测试内容项
1. 默认值的使用是否正常
2. mappingForValue是否正常。
3.
3.
*/


Expand All @@ -25,67 +25,33 @@ class Test3ViewController: BaseViewController {

override func viewDidLoad() {
super.viewDidLoad()



let dict1: [String: Any] = [
"age": 10,
"name": "Mccc",
"location": [
"province": "Jiang zhou",
"city": "Su zhou",
"code": "10000",
"msg": "成功",
"data": [
"guideSvga": "guideSvga",
"guideOnevga": "guideOnevga",
"loadingSvga": "loadingSvga",
"loadingSvgaBackgroundColor": "loadingSvgaBackgroundColor",
]

]

if let jsonData = try? JSONSerialization.data(withJSONObject: dict1, options: []) {
// Successfully converted Dictionary to Data
print("JSON Data:", jsonData)

do {
let obj = try JSONDecoder().decode(Model.self, from: jsonData)
print("obj = ", obj)

} catch {
print("error = ", error)
}

// If you want to convert it back to a String for debugging purposes
if let jsonString = String(data: jsonData, encoding: .utf8) {
print("JSON String:", jsonString)
}
}

if let model = Model.deserialize(from: dict1) {
smartPrint(value: model)
print("\n")
let dict = model.toDictionary() ?? [:]
print(dict)
}
guard let model = ResponseData<HomeListModel>.deserialize(from: dict1) else { return }
print(model)
}
}




extension Test3ViewController {
struct Model: SmartCodable {
var name: String = ""
@IgnoredKey
var ignore: String = ""
@IgnoredKey
var ignore2 = ""
var age: Int = 0
var location: Location?

struct HomeListModel: SmartCodable {
var guideSvga = ""
var guideOnevga = ""
var loadingSvga = ""
var loadingSvgaBackgroundColor = ""
}

struct Location: SmartCodable {
var province: String = ""

// 忽略解析
@IgnoredKey
var city: String = "area123"
struct ResponseData<T>: SmartCodable where T: SmartCodable {
var code = ""
var msg = ""
var data: T?
}
}


47 changes: 31 additions & 16 deletions Example/SmartCodable/TestViewController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -35,37 +35,52 @@ class TestViewController: BaseViewController {
override func viewDidLoad() {
super.viewDidLoad()
let jsonString = """
[
{
"enjoyCount": 462,
"talkCount": null,
"enjoyCount": 1,
"commentCount": 1,
},
{
"enjoyCount": 2,
"commentCount": 2,
},
{
"enjoyCount": 2,
"commentCount": 2,
}
]
"""

guard let model = RecommendModel.deserialize(from: jsonString) else {
guard let models = [RecommendModel].deserialize(from: jsonString) else {
return
}
print(models)
print("\n")

print(model)
let uniqueRecommends = Array(Set(models))
print(uniqueRecommends)
}


struct RecommendModel: SmartCodable {
struct RecommendModel: SmartCodable, Equatable, Hashable {

/// 点赞数
var enjoyCount: Int = 0
/// 评论数
var commentCount: Int = 0



static func mappingForKey() -> [SmartKeyTransformer]? {
[
CodingKeys.commentCount <--- ["commentCount","talkCount","postCommentCount","topicCommentCount","topicTalkCount", "articleCommentCount"],
CodingKeys.enjoyCount <--- ["articleEnjoyCount","enjoyCount","topicEnjoyCount","postEnjoyCount"],
]
@IgnoredKey
var priceText: NSAttributedString? // 价格富文本


static func == (lhs: RecommendModel, rhs: RecommendModel) -> Bool {
return true
}

// 手动实现 Hashable 协议
func hash(into hasher: inout Hasher) {
hasher.combine(enjoyCount)
hasher.combine(commentCount)
}
}

}
2 changes: 1 addition & 1 deletion SmartCodable.podspec
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@

Pod::Spec.new do |s|
s.name = 'SmartCodable'
s.version = '4.2.3'
s.version = '4.2.4'
s.summary = '数据解析库'

s.homepage = 'https://github.com/intsig171'
Expand Down
6 changes: 5 additions & 1 deletion SmartCodable/Classes/JSONDecoder/Decoder/KeysMapper.swift
Original file line number Diff line number Diff line change
Expand Up @@ -44,11 +44,15 @@ struct KeysMapper {
type.mappingForKey()?.forEach { mapping in
for oldKey in mapping.from {
let newKey = mapping.to.stringValue

// 先移除数据中原本的字段
newDict.removeValue(forKey: newKey)

if let value = newDict[oldKey] as? JSONValue, value != .null {
newDict[newKey] = newDict[oldKey]
break
} else { // Handles the case of a custom parsing path.
if newDict[newKey] == nil, let pathValue = newDict.getValue(forKeyPath: oldKey) {
if let pathValue = newDict.getValue(forKeyPath: oldKey) {
newDict.updateValue(pathValue, forKey: newKey)
}
}
Expand Down

0 comments on commit 26a667a

Please sign in to comment.