HungCLo HungCLo - 7 months ago 12
Swift Question

How to create a embedded JSON Object and return to String in Swift?

My code.swift is below :

public class Test {

var testA: String = ""
var testB: String = ""

let T_testA : String = "testA"
let T_testB : String = "testB"

init(testA: String, testB: String) {
self.testA = testA
self.testB = testB
}

func toString() -> String? {
let jsonDic : [String: AnyObject] = [
T_testA: testA,
T_testB: testB,
]
do {
let jsonObject = try NSJSONSerialization.dataWithJSONObject( jsonDic, options: NSJSONWritingOptions.PrettyPrinted)

return String(data: jsonObject, encoding: NSUTF8StringEncoding)
} catch {
return nil
}
}
}


In my Tests.swift

func testPerformanceExample() {

let result1 = Test(testA: {"major": 1, "minor": 2}, testB: "http://google.com")

let result2 = result2.toString()!
print("result2=\n\(result2)")
}


I read similar case Here , It seems a different problem!

Is that possible to create the embedded json object together and return it as a String ?

Answer

If you want to get something from your existing code, use it properly:

let result1 = Test(testA: "{\"major\": 1, \"minor\": 2}", testB: "http://google.com")
let result2 = result1.toString()!
print("result2=\n\(result2)")

But I actually suggest you study this other way instead: make a Swift dictionary, convert this dictionary to JSON data, then convert this data to a String. Then you will get a correct JSON String without risking writing erroneous Strings.