2016-11-10 2 views
-1

Im essayant de convertir un NSDictionary en JSON en utilisant la fonction NSJSONSerialization.dataWithJSONObejectNSJSONSerialization conversion NSDictionary à Hexadécimal

code:

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

    print(jsonData) 
    } catch { 

     print(error) 
    } 

tout va bien, sauf la jsonData est en cours d'impression en hexadécimal?

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

Lorsque cette chaîne hexadécimale est converti en binaire, il fait l'objet enfait égal JSON, mais évidemment, je référençant l'objet JSON tout de suite.

Toutes les idées pour lesquelles cela est le cas?

+1

Comme vous le dites, cette donnée est le codage JSON. Pour voir comme une chaîne que vous devrez convertir les données en une chaîne via 'String (données: jsonData, encodage: .utf8)' mais si vous allez envoyer le JSON sur le réseau, la plupart des cadres veulent juste la Les données – Paulw11

Répondre

1

Vous êtes plus qu'à une étape de la 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!)") 

Les deux exemples doivent être emballés avec do- attraper