HungCLo HungCLo - 6 months ago 7
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: "")

let result2 = result2.toString()!

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 ?


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

let result1 = Test(testA: "{\"major\": 1, \"minor\": 2}", testB: "")
let result2 = result1.toString()!

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.