2016-04-26 49 views
-2

我想创建一个new objectRegisterIn,对象的目标是产生一个json对象字典,并返回一个字符串如何在Swift中将JSONObject作为字符串返回?

这里是我的代码

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,它总是

enter image description here

ViewController

@IBOutlet weak var jsonLabel: UILabel! 
override func viewDidLoad() { 
    super.viewDidLoad() 
    // Do any additional setup after loading the view, typically from a nib. 
    let a = RegisterIn.init(a: "123", b: "456", c: "789", d: 00000) 

    jsonLabel.text = a 
} 

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

回答

1

你永远不会从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 
} 
+0

这只是问题的一半。该行'jsonLabel.text =如果了'另一半。 – rmaddy

+0

啊对,只需要'jsonLabel.text = a.toString()'我猜,但我觉得它真的很奇怪,它实际上击中了函数然后,也许toString以某种方式隐含着一些快速的魔术 – Fonix

+0

你不是指''jsonLabel.text = a.getJSONObject()'? – rmaddy

0

可能

"let jsonObject = try NSJSONSerialization.dataWithJSONObject(jsonDic, options: NSJSONWritingOptions.PrettyPrinted)" 

有问题。 您可以选择null替换PrettyPrinted"options:[])”

相关问题