1

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 ?

3
  • In the class the property testA is declared as String. How can testA in Tests be a dictionary? Commented Apr 27, 2016 at 10:05
  • You should not create JSON String from a Swift String. Instead, make a dictionary/array then convert it to JSON data then convert it back to JSON String. There's examples in my answers - and of course many others in SO. Commented Apr 27, 2016 at 10:09
  • Replace string to Dictionary still returns error~ Commented Apr 27, 2016 at 10:10

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your help, I think you suggestion is really helpful.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.