Swift 4 - SwiftyJson 比较数组并合并找到的值
Posted
技术标签:
【中文标题】Swift 4 - SwiftyJson 比较数组并合并找到的值【英文标题】:Swift 4 - SwiftyJson compare array and merge found values 【发布时间】:2018-01-15 12:39:08 【问题描述】:我有一个 JSON
对象,其中包含名称和值的列表。我想将另一个数组 [String]
与它进行比较,如果在 JSON
对象值之一中找到该值,则将该值合并到一个新对象中。
我曾尝试在for
循环中使用merge(with)
,但是,它似乎只合并了一个值。
> example: > > json_cat = > > > name: "aaa", > surname: "aaa-1", > grade: "aaa-2" > , > > name: "bbb", > surname: "bbb-1", > grade: "bbb-2" > , > > name: "ccc", > surname: "ccc-1", > grade: "ccc-2" > > // > let arraytest:[String] = ["aaa", "ccc", "ddd"] > // array json_cat compare arraytest > result = > name: "aaa", > surname: "aaa-1", > grade: "aaa-2" > , > > name: "ccc", > surname: "ccc-1", > grade: "ccc-2" >
let json_cat: JSON = "json from url"
let arraytest:[String] = ["aaa", "ccc", "ddd"]
var json_cat_array = JSON()
json_cat.forEach( (index, json_p) in
if arraytest.contains(json_p["name"].string!)
//print("\(index) - \(json_p)")
try! json_cat_array.merge(with: json_p)
)
【问题讨论】:
你试过append
吗?
你检查过我的解决方案了吗?
【参考方案1】:
你可以像这样实现你的循环:
json_cat.forEach( (index, json_p) in
if arraytest.contains(json_p["name"].string!)
//print("\(index) - \(json_p)")
json_cat_array[json_p["name"].string!] = json_p
)
merge 功能实际上是用于合并数据。就像在这个例子中一样:
let original: JSON = [
"first_name": "John",
"age": 20,
"skills": ["Coding", "Reading"],
"address": [
"street": "Front St",
"zip": "12345",
]
]
let update: JSON = [
"last_name": "Doe",
"age": 21,
"skills": ["Writing"],
"address": [
"zip": "12342",
"city": "New York City"
]
]
let updated = original.merge(with: update)
// [
// "first_name": "John",
// "last_name": "Doe",
// "age": 21,
// "skills": ["Coding", "Reading", "Writing"],
// "address": [
// "street": "Front St",
// "zip": "12342",
// "city": "New York City"
// ]
// ]
【讨论】:
【参考方案2】:此代码使用 Swift 4 基础 JSON 解析器。 Swift 4 默认有神奇的解析器。
import Foundation
let jsonString = """
[
"surname": "Roxxy",
"grade": "neaou"
,
"name": "Puffi",
"surname": "Chips",
"grade": "meaou"
,
"name": "Taffy",
"surname": "Baby",
"grade": "mew-mew"
]
"""
struct JsonCat: Decodable
let name: String?
let surname: String
let grade: String
struct Cat
let name: String
let surname: String
let grade: String
guard let jsonData = jsonString.data(using: .utf8), let jsonCats = try? JSONDecoder().decode([JsonCat].self, from: jsonData) else
fatalError()
var cats: [Cat] = []
jsonCats.forEach jsonCat in
guard let name = jsonCat.name else
return
let cat = Cat(name: name, surname: jsonCat.surname, grade: jsonCat.grade)
cats.append(cat)
print(cats)
【讨论】:
以上是关于Swift 4 - SwiftyJson 比较数组并合并找到的值的主要内容,如果未能解决你的问题,请参考以下文章
使用 SwiftyJSON 将 JSON 数组反序列化为 Swift 对象
Swift - 使用 SwiftyJSON 从 JSON 中获取字符串数组
将 SwiftyJSON 用于 Swift 3.1 的子数组