2016-04-26 82 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:[])」

相關問題