-1

Im attempting to convert a NSDictionary to JSON using the NSJSONSerialization.dataWithJSONObeject function

Code :

do{
    let jsonData = try NSJSONSerialization.dataWithJSONObject(SerializationHelper.toDictionary(user), options: NSJSONWritingOptions.PrettyPrinted )

    print(jsonData)
    } catch {

        print(error)
    }

all is well except the jsonData is being printed in hexadecimal?

<7b0a2020 22706173 73776f72 6422203a 20227465 7374222c 0a202022 75736572 6e616d65 22203a20 22546573 74220a7d>

When this hexadecimal string is converted to binary it does infact equal the JSON object but obviously I need the JSON object straight away.

Any ideas why this is the case?

mwild
  • 1,483
  • 7
  • 21
  • 41
  • 1
    As you say, that data is the JSON encoding. In order to see it as a string you would need to convert the data to a string via `String(data:jsonData, encoding: .utf8)` but if you are going to send the JSON over the network, most frameworks just want the Data – Paulw11 Nov 10 '16 at 19:39

1 Answers1

1

You are just one step away from the solution:

Swift 3:

let jsonData = try JSONSerialization.data(withJSONObject: dictionary, options: .prettyPrinted)
let jsonString = String(data: jsonData, encoding: .ascii)
print("json string = \(jsonString!)")

Swift 2:

let jsonData = try NSJSONSerialization.dataWithJSONObject(dictionary, options: .PrettyPrinted )
let jsonString = String(data: jsonData, encoding: NSASCIIStringEncoding)
print("json string = \(jsonString!)")

Both examples should be wrapped with do-catch

alexburtnik
  • 7,661
  • 4
  • 32
  • 70