我有这个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