2017-08-04 47 views
0

我有一個JSON字符串:如何從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 { 

     } 
    } 
    } 
} 

上午我在做這正確嗎?請查看此代碼。

+0

你好你有什麼期望輸出 –

回答

1

先轉換JSON響應字典,您可以用輕鬆地拿到鑰匙和價值

let keys = jsonDict.flatMap { $0.0 } 

OUTPUT [ 「身份」, 「數據」, 「消息」]

對於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] 

AFTER UPDATE

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