2017-04-26 55 views
1

这是一个简单的问题。我不知道(也不能自己弄清楚)正确的术语是用于“编辑”从JSON代码接收的数据。这里是我当前的代码:Swift 3&JSON - 如何编辑从数据库接收的数据?

// Create a url and a session to load it in the background. 
let url = URL(string: "http://api.fixer.io/latest") 
let task = URLSession.shared.dataTask(with: url!) { (data, response, error) in 

    if error == nil { 

     // Try to extract some content from the data. 
     if let content = data { 
      do { 

       // Try to create an array out of the extracted data content. 
       let jsonResult = try JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject 

       // Search for specific objects in the array. 
       if let rates = jsonResult["rates"] as? NSDictionary { 
        print("Rates: \(rates)\n\n") 
        if let currency = rates["USD"] { 
         // Output of line below is – "Currency: \"1.0893\"" 
         print("Currency: \(currency)") 
        } 

       } 

      } catch { 
       print("Error deserializing the JSON:\n\(String(describing: error))") 
      } 
     } 

    } else { 
     print("Error creating the URLSession:\n\(String(describing: error))") 
    } 

} 

// Begin using the URLSession to extract the data. 
task.resume() 

正如你可以在上面看到,我从一个URL使用JSON得到一些数据,然后提取特定的数据集,我正在加标题ratescurrency

但是,我无法在Web上的任何地方找到编辑数据的方法。例如:假设我想将currency的值改为等于“$ 230”而不是“1.0893”。什么是必要的术语/代码去改变它?另一个例子是,如果我想添加另一个对象到rates词典。如果我想添加或类似的东西呢?我不懂这方面的具体语法。我需要帮助!

编辑 - 是的,我试图改变数据库本身,这种方式,当信息从它后面拉,这是随着我现在做的更改而更新。在我上面的例子中,我说我可以将currency更改为“230美元”。那么,我希望它永久保留在数据库中,这样当我稍后提取它的值时,而不是仍然是“1.0893”,现在它是我改变它的值。

这个词是“推?”吗?我想对数据库本身进行更改。

+0

如果您从URL获取数据,则需要将修改后的数据发送回另一个URL以告诉数据库进行更新。您可能会将数据序列化回JSON并使用另一个'URLSession'来发布它,但是您发送它的具体位置以及格式化方式取决于您要修改的数据库,其Web API以及您的访问级别。 – Robert

回答

0

解析JSON到自定义结构或类,例如

struct Currency { 
    let abbrev : String 
    var value : Double 
    var myCurrency : Bool 

    var dictionaryRepresentation : [String:Any] { 
     return ["abbrev" : abbrev, "value" : value, "myCurrency" : myCurrency] 
    } 
} 

var currencies = [Currency]() 

abbrev构件是一个常数(let),其他成员是变量。

... 

     // Try to create an array out of the extracted data content. 
     let jsonResult = try JSONSerialization.jsonObject(with: content) as! [String:Any] 

     if let rates = jsonResult["rates"] as? [String:Double] { 
      for (abbrev, value) in rates { 
       let myCurrency = abbrev == "USD" 
       currencies.append(Currency(abbrev: abbrev, value: value, myCurrency: myCurrency)) 
      } 
     } 

该代码使用本机Dictionary。无论如何,.mutableContainers在Swift中是无用的。

+0

好的,所以在我创建这个全局数组'货币'后,然后将提取的值附加到变量'myCurrency'中,该数据如何被添加到数据库中?我知道如何将这些数据导入到我的Xcode项目中,但是如何将其他数据放回到数据库本身? –

+0

我没有知道你想把对象写回服务器。那么在更改数据之后,您需要将数组映射回JSON和Web界面以接收和处理数据。 – vadian

+0

是的,那正是我的问题。我不知道如何将数据转换回JSON格式并将其发送回数据库。 –