From 06328698ed0db61dd9767e3a8faadaa63b0a9d6c Mon Sep 17 00:00:00 2001 From: Quentin Jin Date: Tue, 3 Sep 2019 21:51:52 +0800 Subject: [PATCH] JSON should also allow key to contain dots. --- KakaJSON/Extension/Dictionary+KJ.swift | 4 +++ .../JSON_To_Model/JTM_05_KeyMapping.swift | 25 +++++++++++++++++++ 2 files changed, 29 insertions(+) diff --git a/KakaJSON/Extension/Dictionary+KJ.swift b/KakaJSON/Extension/Dictionary+KJ.swift index 5125839..9285b7f 100644 --- a/KakaJSON/Extension/Dictionary+KJ.swift +++ b/KakaJSON/Extension/Dictionary+KJ.swift @@ -76,6 +76,10 @@ extension Dictionary where Key == String { } private func _value(stringKey: String) -> Any? { + if let value = self[stringKey] { + return value + } + let subkeys = stringKey.split(separator: ".") var value: Any? = self for subKey in subkeys { diff --git a/KakaJSONTests/JSON_To_Model/JTM_05_KeyMapping.swift b/KakaJSONTests/JSON_To_Model/JTM_05_KeyMapping.swift index c088a8f..a8074e1 100644 --- a/KakaJSONTests/JSON_To_Model/JTM_05_KeyMapping.swift +++ b/KakaJSONTests/JSON_To_Model/JTM_05_KeyMapping.swift @@ -234,6 +234,31 @@ class JTM_05_KeyMapping: XCTestCase { XCTAssert(dog.toy?.price == toy.price) } + func testComplex_JSONKeyWithDot() { + struct Team: Convertible { + var name: String? + var captainName: String? + + func kj_modelKey(from property: Property) -> ModelPropertyKey { + switch property.name { + case "captainName": return "captain.name" + default: return property.name + } + } + } + + let teamName = "V" + let captainName = "Quentin" + + let json: [String: Any] = [ + "name": teamName, + "captain.name": captainName, + ] + let team = json.kj.model(Team.self) + XCTAssert(team.name == teamName) + XCTAssert(team.captainName == captainName) + } + func testConfig1() { // Global Config ConvertibleConfig.setModelKey { property in