我有這個JSON文件:遞歸函數來代替JSON對象
[
{
"person": {
"@id": "value1",
"name": "Mattia"
},
"person1": {
"@ref": "value1"
},
"subPersons": [
{
"@id": "value2",
"name": "Luca",
"key": {
"@ref": "value1"
}
},
{
"@ref": "value1"
},
{
"@id": "value3",
"subsubPersons": [
{
"again": {
"@ref": "value2"
}
}
]
}
],
"key": {
"subKey": {
"@ref": "value1"
}
}
}
]
我需要映射包含@id因此與映射相關@id值替換所有@ref值的所有對象。我想獲得此:
[
{
"person": {
"@id": "value1",
"name": "Mattia"
},
"person1": {
"@id": "value1",
"name": "Mattia"
},
"subPersons": [
{
"@id": "value2",
"name": "Luca",
"key": {
"@id": "value1",
"name": "Mattia"
}
},
{
"@id": "value1",
"name": "Mattia"
},
{
"@id": "value3",
"subsubPersons": [
{
"again": {
"@id": "value2",
"name": "Luca",
"key": {
"@id": "value1",
"name": "Mattia"
}
}
}
]
}
],
"key": {
"subKey": {
"@id": "value1",
"name": "Mattia"
}
}
}
]
我使用這個類來代替值:
import UIKit
import Alamofire
import AlamofireObjectMapper
import ObjectMapper
import SwiftyJSON
import SwiftDate
import Async
class FindAndReplace {
var ids = Dictionary<String, JSON>()
var dictChanged = Dictionary<String, JSON>()
var isDictInit: Bool = false
/*
* Find and Replace
*/
func findAndReplace (json: JSON) -> JSON {
findJSOGids(json)
let replaced = replaceJSOGrefs(json, ids: ids)
return replaced
}
/*
* Find "@id" keys and map values related
*/
func findJSOGids (value: JSON) {
for (key, subJson): (String, JSON) in value {
if (key == "@id") {
let mValueForKey = value[key].stringValue
ids[mValueForKey] = value
}
if (subJson.type == Type.Dictionary || subJson.type == Type.Array) {
findJSOGids(subJson)
}
}
}
/*
* Replace "@ref" keys with fields mapped in ids
*/
func replaceJSOGrefs (var value: JSON, var ids: Dictionary<String, JSON>) -> JSON {
if (value.type == Type.Dictionary) {
var result = Dictionary<String, JSON>()
for (key, subJson): (String, JSON) in value {
if (key == "@ref") {
let mValueForKey = value[key].stringValue
var isReplaced = false
while (isReplaced == false) {
for (idKey, _): (String, JSON) in ids[mValueForKey]! {
if (idKey == "@ref") {
print("found a @ref in dictionary")
let dictValueReplaced = replaceJSOGrefs(ids[mValueForKey]!, ids: ids)
ids.updateValue(dictValueReplaced, forKey: mValueForKey)
}
}
}
return ids[mValueForKey]!
} else {
result[key] = replaceJSOGrefs(subJson, ids: ids)
}
}
return JSON(result)
} else if (value.type == Type.Array) {
var result = [JSON]()
for (_, subJson): (String, JSON) in value {
result.append(replaceJSOGrefs(subJson, ids: ids))
}
return JSON(result)
} else {
return value
}
}
}
它的工作原理,但它忽略了一些@ref值。
有人可以幫我嗎?
在此先感謝。
編輯
我使用ObjectMapper映射對象。
你一定對於任何給定字典「深度」,其中的一個關鍵'@ ref'存在,關鍵'@ id'不?這樣你就不會覆蓋一個給定的鍵值對時「改變」,他們'@ ref'鍵 - 值對以'@ id'。 – dfri
@dfri我110%確定「@id」鍵存在廣告是唯一的 – Jigen