How to convert JSON to String in ios Swift?

Here is the code for the next Json exit:

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" : " 01034_186893@gmail.com "], ["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{} 

Having printed jsonObject, I got this one.

[{"value": "pay", "name": "action"}, {"value": {"rows": [{"price": "1", "quantity": "1", "cost" : "1", "currency": "INR", "itemId": "DN001", "title": "Donation for SMSF India - General Fund"}], "total": 1}, "name": "cartJsonData "}, {" value ":" Chennai "," name ":" center "}, {" value ":" 503 "," name ":" flatNumber "}, {" value ":" "," name " : "panNumber"}, {"name": "payWith"}, {"value": "Monthly", "name": "reminderFrequency"}, {"name": "shipToAddr1"}, {"name": " shipToAddr2 "}, {" name ":" shipToCity "}, {" value ":" India "," name ":" shipToCountryName "}, {" value ":" 01034_186893@gmail.com "," name ":" shipToEmail "}, {" value ":" 4480101010 "," name ":" shipToFirstName "}, {" name ":" shipToLastName "}, {" value ":" 4480101010 "," name ":" shipToPhone "}, { "name": "shipToState"}, {"name": "shipToZip"}, {"value": "null", "name": "userId"}, {"value": "IN", "name": "shipToCountry"}]

And I want JSON to be in the following format.

[{"name": "action", "value": "pay"}, {"name": "cartJsonData", "" cost ":" {\ "total \": 1, \ "rows \": [ {\ "itemId \": \ "DN002 \", \ "title \": \ "Donation for SMSF India - General Fund \" \ "amount \": \ "100 \", \ "currency \": \ " INR \ ", \" price \ ": \" 1 \ ", \" cost \ ": \" 100 \ "}]}"}, {"name": "center", "value": "Chennai"} , {"name": "flatNumber", "" value ":" "}, {" name ":" panNumber "," value ":" ASSDDBBDJD "}, {" name ":" payWith "}, {" name ":" reminderFrequency "," value ":" Monthly "}, {" name ":" shipToAddr1 "}, {" name ":" shipToAddr2 "}, {" name ":" shipToCity "}, {" name ": "shipToCountryName", "value": "India"}, {"name": "shipToEmail", "value": " Sudhakar@gmail.com "}, {"name": "shipToFirstName", "value": "Raju" }, {"name": "shipToLastName"}, {"name": "shipToPhone", "value": "1234567890"}, {"name": "shipToState"}, {"name": "shipToZip"}, {"name": "userId", "value": "null"}, {"n ame ":" shipToCountry "," value ":" IN "}]

How can I do that? Only the value in cartJsonData needs to be changed. Can someone help me with this to solve this problem?

+20
source share
5 answers

Try it.

 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) } } 
+34
source

Swift (as of July 10, 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) } } 
+9
source

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

Using

 stringify(json: ["message": "Hello."]) 
+9
source

Using the new Encodable-based API, you can get the string version of the JSON file using the String initializer (init: encoding). I ran this on the playground and the last printed expression gave me

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

It looks like the format uses the minimum number of characters in detail.

 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) } } 
+1
source

An easy way to convert a JSON object to a string: 1. First create a JSON index value, for example, JSONObject ["FIELDNAME"] 2. Use the .stringValue property to get the actual string equivalence (jsonObject ["fieldName"]. StringValue)

0
source

Source: https://habr.com/ru/post/1246291/


All Articles