I have this json file:
[
{
"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"
}
}
}
]
I need to map all objects that contains a @id so replace all @ref values with related @id values mapped. I'd like to obtain this:
[
{
"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"
}
}
}
]
I'm using this class to replace values:
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)
retu 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
//manca controllo su ids, se contiene delle @ref delle sostituirle
//********
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)
}
}
}
retu ids[mValueForKey]!
} else {
result[key] = replaceJSOGrefs(subJson, ids: ids)
}
}
retu JSON(result)
} else if (value.type == Type.Array) {
var result = [JSON]()
for (_, subJson): (String, JSON) in value {
result.append(replaceJSOGrefs(subJson, ids: ids))
}
retu JSON(result)
} else {
retu value
}
}
}
It works but it misses some @ref values.
Can someone please help me?
Thanks in advance.
