46

Here is the code for the below Json output:

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

By printing 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 the JSON to be in the below format.

[{ “name”: “action”, “value”: “pay” }, { “name”: “cartJsonData”, “value”: “{\”total\”:1,\”rows\”:[{\”itemId\”:\”DN002\”,\”title\”:\”Donation for SMSF India - General Fund\”,\”quantity\”:\”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” }, { “name”: “shipToCountry”, “value”: “IN” }]

How can it be done? Only the value in cartJsonData needs to be changed. Can someone help me on this to solve it?

Moin Shirazi
  • 4,372
  • 2
  • 26
  • 38
Divya Ponnuraj
  • 518
  • 1
  • 4
  • 7
  • Using the `try` syntax `jsonObject` will never be `nil` – vadian Apr 02 '16 at 08:02
  • What is it that bothers you with the output? It seems like it's a valid json. I am guessing that you don't like the fact that your keys and values order is changed.. In this case you can't fix it, since dictionary does not preserve order of keys, i mean you could still work around that somehow by outputting the json yourself or using some other lib to do that, but that doesn't sound like it's worth it. – igrek Nov 29 '17 at 15:04
  • btw, maybe you'd be interested in `WritingOptions.sortedKeys` option – igrek Nov 29 '17 at 15:09

7 Answers7

49

Try this.

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: .utf8) // the data will be converted to the string
            print(convertedString) // <-- here is ur string  
            
        } catch let myJSONError {
            print(myJSONError)
        }
      
    }
Mamad Farrahi
  • 394
  • 1
  • 5
  • 20
ak sacha
  • 2,149
  • 14
  • 19
24

Swift (as of December 3, 2020)

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)
    }
    
}
BennyTheNerd
  • 3,930
  • 1
  • 21
  • 16
  • 2
    Swift 3 is more than using the changed API syntax. In Swift 3 JSON is `Any`, the `options` parameter can be omitted (prettyPrinted is not intended in the question), `convertedString` can never be `nil` (even in Swift 2) and in the `catch` scope you can simply `print(error)` without a `let` assignment. – vadian Sep 11 '17 at 16:27
14

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."])
Minh Hoang
  • 183
  • 1
  • 2
  • 8
  • If you need to compare Json to Json, then add in here the use of sorting - your options should look like this: options: [JSONSerialization.WritingOptions.sortedKeys, JSONSerialization.WritingOptions.prettyPrinted]. Otherwise the order of keys can be different and so logically identical structures might produce non-identical strings. – Andy Weinstein Jul 26 '20 at 20:10
  • See also https://stackoverflow.com/a/46037539/826946 which is where I got the sorting parameter from. – Andy Weinstein Jul 26 '20 at 21:05
5

Using the new Encodable based API, you can get the string version of a JSON file using String(init:encoding) initialiser. I ran this in a Playground and the last print statement gave me

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

It seems that the format uses the minimum number of characters by 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)
    }
}
MarkAurelius
  • 1,203
  • 1
  • 14
  • 27
3
  • Swift 4.x
  • xcode 10.x

if you are using Swifty JSON

var stringfyJSOn  = yourJSON.description

For Reference or more information

https://github.com/SwiftyJSON/SwiftyJSON

Sazid Iqabal
  • 409
  • 2
  • 21
Abdul Karim
  • 4,359
  • 1
  • 40
  • 55
  • This answer is not working. If the JSON data is a Data object it does not work. You need to make first this operation: let data = try JSONSerialization.data(withJSONObject: json, options: options) if let string = String(data: data, encoding: String.Encoding.utf8) { return string } – Diego Jiménez Oct 13 '20 at 17:20
  • @wazowski thanks for adding a useful comment, but as per question it was just JSON and nothing mention as JSON data , but yeah if it is data your solu. will work, plz read the question again – Abdul Karim Oct 14 '20 at 04:36
  • you are right the question asks a thing, but the code is telling other, when you receive a data object from the url session you do not receive a Json object like an [String:Any] dictionary, the code of the question is not showing the real JSON data, the question should be 'how can I convert a dictionary to string?'. – Diego Jiménez Oct 14 '20 at 11:13
  • 1
    it's an incredibly bad idea to use any library for json nowadays in iOS. it is absolutely built in to Swift/iOS – Fattie Oct 24 '21 at 15:37
0

A simple way to convert a JSON object to a String is: 1. First create a JSON subscript value e.g. jsonObject["fieldName"] 2. Use the '.stringValue' property to retrieve the actually String equivalence (jsonObject["fieldName"].stringValue)

tonderaimuchada
  • 215
  • 2
  • 6
0

Xcode 11, converted String to NSString is working for me.

func jsonToString(json: AnyObject) -> String{
    do {
        let data1 = try JSONSerialization.data(withJSONObject: json, options: JSONSerialization.WritingOptions.prettyPrinted)
        let convertedString = String(data: data1, encoding: String.Encoding.utf8) as NSString? ?? ""
        debugPrint(convertedString)
        return convertedString as String
    } catch let myJSONError {
        debugPrint(myJSONError)
        return ""
    }
}
Jignesh Kanani
  • 223
  • 1
  • 4
  • 18
  • 1
    when I use this I get this error "Argument type 'JSON' expected to be an instance of a class or class-constrained type" – grooot Feb 19 '21 at 09:24