如何从swift3中的JSON字符串中分别获取键和值?
Posted
技术标签:
【中文标题】如何从swift3中的JSON字符串中分别获取键和值?【英文标题】:How to get the keys and values separately from the JSON string in swift3? 【发布时间】:2017-08-04 05:53:51 【问题描述】:我有一个 JSON 字符串:
"messages": null,
"data": [
"id": 27,
"key": "ABC",
"value": "5",
"description": "Hi all"
,
"id": 28,
"key": "DEF",
"value": "1",
"description": "I am here"
]
"status": 0
现在我需要获取键的值并使用核心数据中存在的值对其进行更新。 为此,我正在使用代码:
func updateAllRecords(responseArray: [ApplicationSettingsDataResponse])
for settingsObject in responseArray
if #available(ios 10.0, *)
let request = NSFetchRequest<ApplicationSettings>(entityName: "ApplicationSettings")
do
let context = persistentContainer.viewContext
let searchResults = try context.fetch(request)
for settingsKeys in searchResults
if settingsKeys.key == settingsObject.key
settingsKeys.value = settingsObject.value
try context.save()
catch
print ("There was an error")
else
我这样做对吗?请查看此代码。
【问题讨论】:
您好,您的预期输出是什么 【参考方案1】:首先将json响应转换为字典,您可以轻松获取键和值
let keys = jsonDict.flatMap $0.0
输出 [“状态”、“数据”、“消息”]
更多信息我创建了演示
import UIKit
func convertToDictionary(text: String) -> [String:Any]?
if let data = text.data(using: .utf8)
do
return try JSONSerialization.jsonObject(with: data, options: []) as? Dictionary
catch
print(error.localizedDescription)
return nil
let str = "\"messages\": 0,\"data\": [\"id\": 27,\"key\": \"ABC\",\"value\": \"5\",\"description\": \"Hi all\",\"id\": 28,\"key\": \"DEF\",\"value\": \"1\",\"description\": \"I am here\"],\"status\": 0"
let str2 = "\"messages\": 1,\"data\": [\"id\": 27,\"key\": \"ABC\",\"value\": \"5\",\"description\": \"Hi all\",\"id\": 28,\"key\": \"DEF\",\"value\": \"1\",\"description\": \"I am not here\"],\"status\": 1"
let replaceWithDict:[String:Any] = convertToDictionary(text: str) ?? ["test":"test"]
var resultDict:[String:Any] = convertToDictionary(text: str2) ?? ["test":"test"]
let keys = replaceWithDict.flatMap $0.0
print(resultDict)
for key in keys
resultDict.updateValue(replaceWithDict[key], forKey: key)
print(resultDict)
输出
更新前
["status": 1, "data": <__NSArrayI 0x608000034900>(
description = "Hi all";
id = 27;
key = ABC;
value = 5;
,
description = "I am not here";
id = 28;
key = DEF;
value = 1;
)
, "messages": 1]
更新后
["status": Optional(0), "data": Optional(<__NSArrayI 0x600000033460>(
description = "Hi all";
id = 27;
key = ABC;
value = 5;
,
description = "I am here";
id = 28;
key = DEF;
value = 1;
)
), "messages": Optional(0)]
【讨论】:
以上是关于如何从swift3中的JSON字符串中分别获取键和值?的主要内容,如果未能解决你的问题,请参考以下文章
如何在iOS swift的tableview中使用json响应中的键和值?
$.ajax 从 php 获取 json_encode($arr) 之后的对象,但是如何在 jQuery 中获取键和值?
Swift 3 - 如何从包含字符串的索引中读取 json 输出