HungCLo HungCLo - 7 months ago 8
Swift Question

How to return a JSONObject as a String in swift?

I would like to create a new object called RegisterIn, the target of the object is to generate a json object as dictionary and return as a String

Here is my code

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
}
}


At function getJSONObject, I think it return a jsonObject as [String: AnyObject]. In my ViewController, I want to assign it to a Label.text, it always enter image description here

my 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
}


I think I have to change some code in RegisterIn class, really need some help!

Answer

you never returned a string from getJSONObject(), try

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
}
Comments