如何在swift中将JSONObject作为String返回?

时间:2016-04-26 03:37:08

标签: ios json string swift

我想创建一个名为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,它总是

enter image description here

我的Label.text

ViewController

我想我必须在RegisterIn类中更改一些代码,真的需要一些帮助!

2 个答案:

答案 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;