我想创建一个名为new object
的{{1}},该对象的目标是生成一个RegisterIn
对象作为字典并返回为字符串
这是我的代码
json
在功能public class RegisterIn {
private var a : String = "" //required
private var b: String = "" //required
private var c: String = "" //required
private var d: Int = 0 //required
private let BD_a : String = "a"
private let BD_b : String = "b"
private let BD_c : String = "c"
private let BD_d : String = "d"
init(a: String, b: String, c: String, d: Int) {
self.a = a
self.b = b
self.c = c
self.d = d
}
func getJSONObject() {
let jsonDic : [String: AnyObject] = [
BD_a: a,
BD_b: b,
BD_c: c,
BD_d: d
]
do {
let jsonObject = try NSJSONSerialization.dataWithJSONObject( jsonDic, options: NSJSONWritingOptions.PrettyPrinted)
} catch let error as NSError {
print(error)
}
}
func toString() {
return String(getJSONObject()) <- this line occur error
}
}
,我认为它会返回getJSONObject
。在我的jsonObject as [String: AnyObject]
中,我想将其分配给ViewController
,它总是
我的Label.text
:
ViewController
我想我必须在RegisterIn类中更改一些代码,真的需要一些帮助!
答案 0 :(得分:2)
您从未从getJSONObject()
返回字符串,请尝试
func getJSONObject() -> String? {
let jsonDic : [String: AnyObject] = [
BD_a: a,
BD_b: b,
BD_c: c,
BD_d: d
]
do {
let jsonObject = try NSJSONSerialization.dataWithJSONObject( jsonDic, options: NSJSONWritingOptions.PrettyPrinted)
return NSString(data: jsonObject, encoding:NSUTF8StringEncoding)
} catch let error as NSError {
print(error)
return nil
}
}
func toString() {
return getJSONObject() //to be more correct, but this function is sort of redundant, just call getJSONObject directly, but up to you whats the best
}
答案 1 :(得分:0)
可能是
"let jsonObject = try NSJSONSerialization.dataWithJSONObject( jsonDic, options: NSJSONWritingOptions.PrettyPrinted)"
有问题。
您可以使用null
选项来替换PrettyPrinted
。
"options:[]
)&#34;