2016-04-02 12 views
5

Ecco il codice per il seguito di uscita JSON:Come convertire JSON in String in ios Swift?

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{} 

Stampando JsonObject, ho ottenuto questo.

[{ "valore": "paga", "name": "" azione"}, { "valore": { "righe": [{ "prezzo": "1", "quantità": "1", "costo": "1", "valuta": "INR", "itemId": "DN001", "titolo": "Donazione per SMSF India - Fondo generale" }], "totale": 1}, "nome": "cartJsonData"}, {"valore": "Chennai", "nome": "center"}, {"value": "503", "name": "flatNumber"}, { "valore": "", "nome": "panNumber"}, {"nome": "payWith"}, {"valore": "Mensile", "nome": "reminderFrequency"}, {"nome" : "shipToAddr1"}, { "nome": "shipToAddr2"}, {"nome": "shipToCity"}, {"valore": "India", "nome": "shipToCountryName" }, {"valore": "[email protected]", "nome": "shipToEmail"}, {"valore": "4480101010", "nome": "shipToFirstName"}, {"nome": " shipToLastName "}, {" value ": " 4480101010 "," name ":" shipToPhone "}, {" name ":" shipToState "}, { " name ":" shipToZip "}, {" value ":" null", "name": "userID"}, { "valore": "iN", "name": "shipToCountry"}]

E voglio il JSON sia nel formato di seguito.

[{ “name”: “azione”, “valore”: “pagare”}, { “name”: “cartJsonData”, “valore”: “{\” \ totale”: 1, \ "Rows \": [{\ "itemId \": \ "DN002 \", \ "title \": \ "Donazione per SMSF India - Generale Fondo \", \ "quantità \": \ "100 \ ", \" Valuta \ ": \" INR \ ", \" prezzo \ ": \" 1 \ ", \" costo \ ": \" 100 \ "}]}" }, {"nome": " center "," value ":" Chennai "}, {" nome ":" flatNumber ", " valore ":" "}, {" nome ":" panNumber "," valore ":" ASSDDBBDJD "}, { "Name": "payWith"}, {"name": "reminderFrequency", "val ue ":" Mensile " }, {" nome ":" shipToAddr1 "}, {" nome ":" shipToAddr2 "}, {" nome ": " shipToCity "}, {" nome ":" shipToCountryName "," value ":" India "}, { " nome ":" shipToEmail "," valore ":" [email protected] "}, {" nome ": " shipToFirstName "," value ":" Raju "}, {"Nome": "shipToLastName"}, { "nome": "shipToPhone", "valore": "1234567890"}, {"nome": "shipToState"}, {"nome": "shipToZip"}, { “name”: “userID”, “valore”: “null”}, { “name”: “shipToCountry”, “valore”: “IN”}]

Come può essere fatto? È necessario modificare solo il valore in cartJsonData. Qualcuno può aiutarmi a risolverlo?

+0

uso di '' sintassi try' jsonObject' sarà mai 'quelle negative – vadian

+0

Che cos'è che ti dà fastidio con l'uscita? Sembra che sia un vero peccato. Immagino che non ti piaccia il fatto che il tuo ordine di chiavi e valori sia cambiato .. In questo caso non puoi aggiustarlo, dato che il dizionario non conserva l'ordine delle chiavi, voglio dire che potresti comunque aggirare il problema in qualche modo emettendo il json da soli o usando qualche altra lib per farlo, ma non sembra che ne valga la pena. – igrek

+0

btw, forse saresti interessato all'opzione 'WritingOptions.sortedKeys' – igrek

risposta

24

Prova questo.

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) 
     } 

    } 
+0

Grazie! Anche la conversione di Swift 3.1 è sotto! – BennyTheNerd

4

Swift 3,1

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) 
    } 

} 
+1

Swift 3 è più che usare la sintassi dell'API modificata. In Swift 3 JSON è 'Any', il parametro' options' può essere omesso (prettyPrinted non è inteso nella domanda), 'convertedString' non può mai essere' nil' (nemmeno in Swift 2) e nella portata 'catch' tu può semplicemente 'stampare (errore)' senza un incarico 'let'. – vadian

1

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 "" 
} 

Uso

stringify(json: ["message": "Hello."])