如何从swift3中的JSON字符串中分别获取键和值?

时间:2017-08-04 05:53:51

标签: json core-data swift3

我有一个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 个答案:

答案 0 :(得分:1)

首先将json响应转换为字典,然后使用

轻松获取键和值
let keys = jsonDict.flatMap { $0.0 }

<强>输出 [&#34;状态&#34;,&#34;数据&#34;,&#34;消息&#34;]

对于moreinfo,我创建了演示

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)]