本文介绍了将JSON/NSDictionary反序列化为Swift对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有一种方法可以正确反序列化对Swift对象响应的JSON响应.使用DTO作为固定JSON API的容器?
Is there a way to properly deserialize a JSON response to Swift objects resp. using DTOs as containers for fixed JSON APIs?
类似于 http://james.newtonking.com/json 之类的东西,或类似Java中的示例
Something similar to http://james.newtonking.com/json or something like this example from Java
User user = jsonResponse.readEntity(User.class);
其中jsonResponse.toString()
类似于
{
"name": "myUser",
"email": "[email protected]",
"password": "passwordHash"
}
推荐答案
由于您提供了一个非常简单的JSON对象,因此代码已准备就绪,可以处理该模型.如果您需要更复杂的JSON模型,则需要改进此示例.
Since you give a very simple JSON object the code prepared for to handle that model. If you need more complicated JSON models you need to improve this sample.
您的自定义对象
class Person : NSObject {
var name : String = ""
var email : String = ""
var password : String = ""
init(JSONString: String) {
super.init()
var error : NSError?
let JSONData = JSONString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
let JSONDictionary: Dictionary = NSJSONSerialization.JSONObjectWithData(JSONData, options: nil, error: &error) as NSDictionary
// Loop
for (key, value) in JSONDictionary {
let keyName = key as String
let keyValue: String = value as String
// If property exists
if (self.respondsToSelector(NSSelectorFromString(keyName))) {
self.setValue(keyValue, forKey: keyName)
}
}
// Or you can do it with using
// self.setValuesForKeysWithDictionary(JSONDictionary)
// instead of loop method above
}
}
这就是您使用JSON字符串调用自定义类的方式.
And this is how you invoke your custom class with JSON string.
override func viewDidLoad() {
super.viewDidLoad()
let jsonString = "{ \"name\":\"myUser\", \"email\":\"[email protected]\", \"password\":\"passwordHash\" }"
var aPerson : Person = Person(JSONString: jsonString)
println(aPerson.name) // Output is "myUser"
}
这篇关于将JSON/NSDictionary反序列化为Swift对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!