web-dev-qa-db-fra.com

Comment convertir un fichier JSON en chaîne sous ios Swift?

Voici le code pour la sortie Json ci-dessous:

let params : [[String : AnyObject]]  = [["name" : "action", "value" : "pay" ],["name" : "cartJsonData" , "value" : ["total": 1,"rows":[["quantity": “1” ,"title":"Donation for SMSF India - General Fund","price":"1","itemId":"DN001","cost": “1”,”currency":"INR"]]]], ["name" : "center", "value" : "Chennai"], ["name" : "flatNumber", "value" : "503"], ["name" : "panNumber", "value" : ""], ["name" : "payWith"], ["name" : "reminderFrequency","value" : "Monthly"],  ["name" : "shipToAddr1"], ["name" : "shipToAddr2"], ["name" : "shipToCity"], ["name" : "shipToCountryName" , "value" : "India"], ["name" : "shipToEmail", "value" : “[email protected]"], ["name" : "shipToFirstName" , "value": "4480101010"], ["name" : "shipToLastName"], ["name" : "shipToPhone", "value" : "4480101010"], ["name" : "shipToState"], ["name" : "shipToZip"], ["name" : "userId", "value" : “null”], ["name" : "shipToCountry", "value" : "IN"]]

var jsonObject: NSData? = nil

do {
   jsonObject = try NSJSONSerialization.dataWithJSONObject(params, options: NSJSONWritingOptions())
   print(jsonObject) // This will print the below json. 
} 
catch{}

En imprimant jsonObject, j'ai eu celui-ci. 

[{"valeur": "pay", "nom": "action"}, {"valeur": {"lignes": [{ "prix": "1", "quantité": "1", "coût": "1", "devise": "INR", "itemId": "DN001", "titre": "Don pour SMSF Inde - Fonds général" }], "total": 1}, "nom": "cartJsonData"}, {"valeur": "Chennai", "name": "center"}, {"value": "503", "name": "flatNumber"}, { "valeur": "", "nom": "panNumber"}, {"nom": "payWith"}, {"valeur": "Mensuel", "nom": "rappelFréquence"}, {"nom": "shipToAddr1"}, { "nom": "shipToAddr2"}, {"nom": "shipToCity"}, {"valeur": "Inde", "name": "shipToCountryName"}, {"value": "[email protected]", "nom": "shipToEmail"}, {"valeur": "4480101010", "nom": "shipToFirstName"}, {"name": "shipToLastName"}, {"value": "4480101010", "nom": "shipToPhone"}, {"nom": "shipToState"}, { "name": "shipToZip"}, {"value": "null", "name": "userId"}, { "valeur": "IN", "name": "shipToCountry"}]

Et je veux que le JSON soit dans le format ci-dessous.

[{“Name”: “action”, “value”: “pay”}, {“name”: “cartJsonData”, "valeur": “{\” Total\”: 1, \” rangées\”: [{\” itemId\”: \” DN002\”, \” titre\”: \” Donation pour SMSF Inde - Général Fonds\", \" quantité\": \" 100 ", \" devise\": \" INR\", \" prix\": \" 1\", \" coût\": \" 100\”}]}” }, {“Name”: “center”, “value”: “Chennai”}, {“name”: “flatNumber”, "Valeur": ""}, {"nom": "panNumber", "valeur": "ASSDDBBDJD"}, { “Nom”: “payWith”}, {“nom”: “fréquence de rappel”, “valeur”: “mensuel” }, {“Nom”: “shipToAddr1”}, {“nom”: “shipToAddr2”}, {“nom”: “ShipToCity”}, {“name”: “shipToCountryName”, “value”: “India”}, { “Name”: “shipToEmail”, “value”: “[email protected]”}, {“name”: “ShipToFirstName”, “value”: “Raju”}, {“name”: “shipToLastName”}, { “Name”: “shipToPhone”, “value”: “1234567890”}, {“name”: “ShipToState”}, {“name”: “shipToZip”}, {“name”: “ID utilisateur”, “valeur”: “Null”}, {“name”: “shipToCountry”, “value”: “IN”}]

Comment ceci peut être fait? Seule la valeur dans cartJsonData doit être modifiée. Quelqu'un peut-il m'aider à résoudre ce problème?

13
Divya Ponnuraj

Essaye ça.

func jsonToString(json: AnyObject){
        do {
          let data1 =  try NSJSONSerialization.dataWithJSONObject(json, options: NSJSONWritingOptions.PrettyPrinted) // first of all convert json to the data
            let convertedString = String(data: data1, encoding: NSUTF8StringEncoding) // the data will be converted to the string
            print(convertedString) // <-- here is ur string  

        } catch let myJSONError {
            print(myJSONError)
        }

    }
31
ak sacha

Swift (au 10 juillet 2018)

func jsonToString(json: AnyObject){
    do {
        let data1 =  try JSONSerialization.data(withJSONObject: json, options: JSONSerialization.WritingOptions.prettyPrinted) // first of all convert json to the data
        let convertedString = String(data: data1, encoding: String.Encoding.utf8) // the data will be converted to the string
        print(convertedString ?? "defaultvalue")
    } catch let myJSONError {
        print(myJSONError)
    }

}
8
BennyTheNerd

Swift 4.0

static func stringify(json: Any, prettyPrinted: Bool = false) -> String {
    var options: JSONSerialization.WritingOptions = []
    if prettyPrinted {
      options = JSONSerialization.WritingOptions.prettyPrinted
    }

    do {
      let data = try JSONSerialization.data(withJSONObject: json, options: options)
      if let string = String(data: data, encoding: String.Encoding.utf8) {
        return string
      }
    } catch {
      print(error)
    }

    return ""
}

Usage

stringify(json: ["message": "Hello."])
6
Minh Hoang

À l'aide de la nouvelle API basée sur Encodable, vous pouvez obtenir la version sous forme de chaîne d'un fichier JSON à l'aide de l'initialiseur String (init: encoding). J'ai couru cela dans un terrain de jeu et la dernière déclaration d'impression m'a donné 

json {"year":1961,"month":4}

Il semble que le format utilise le nombre minimum de caractères par détail.

struct Dob: Codable {
    let year: Int
    let month: Int
}

let dob = Dob(year: 1961, month: 4)
print("dob", dob)

if let dobdata = try? JSONEncoder().encode(dob) {
    print("dobdata base64", dobdata.base64EncodedString())
    if let ddob = try? JSONDecoder().decode(Dob.self, from: dobdata) {
        print("resetored dob", ddob)
    }
    if let json = String(data: dobdata, encoding: .utf8) {
      print("json", json)
    }
}
0
MarkAurelius