2016-11-10 4 views
-1

Im Versuch, eine NSDictionary zu JSON konvertieren mit der NSJSONSerialization.dataWithJSONObeject FunktionNSJSONSerialization Umwandlung NSDictionary zu Hexadezimal

Code:

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

    print(jsonData) 
    } catch { 

     print(error) 
    } 

alles gut ist, außer der jsonData in hexadezimalen gedruckt wird?

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

Wenn dieser Hexadezimalstring zu binär umgewandelt wird es tut infact gleich dem Objekt JSON, aber offensichtlich muß ich das JSON-Objekt sofort.

Irgendwelche Ideen, warum dies der Fall ist?

+1

Wie Sie sagen, handelt es sich bei den Daten um die JSON-Codierung. Um es als eine Zeichenkette zu sehen, müssten Sie die Daten in eine Zeichenkette über 'String (Daten: jsonData, encoding: .utf8)' konvertieren, aber wenn Sie die JSON über das Netzwerk senden wollen, wollen die meisten Frameworks die Daten – Paulw11

Antwort

1

Sie sind nur einen Schritt entfernt von der Lösung:

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!)") 

Beide Beispiele mit do- gewickelt werden sollte fangen