48

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" : “[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{}

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": "[email protected]", "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”: “[email protected]” }, { “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?

3
  • Using the try syntax jsonObject will never be nil Commented Apr 2, 2016 at 8: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. Commented Nov 29, 2017 at 15:04
  • btw, maybe you'd be interested in WritingOptions.sortedKeys option Commented Nov 29, 2017 at 15:09

7 Answers 7

52

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)
        }
      
    }
Sign up to request clarification or add additional context in comments.

1 Comment

See note above (stackoverflow.com/a/47725685/826946) about using sorting when you want to produce a canonical string that you can use to compare one JSON to another.
25

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

1 Comment

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.
16

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."])

2 Comments

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.
See also stackoverflow.com/a/46037539/826946 which is where I got the sorting parameter from.
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)
    }
}

Comments

1
  • 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

4 Comments

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 }
@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
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?'.
it's an incredibly bad idea to use any library for json nowadays in iOS. it is absolutely built in to Swift/iOS
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)

Comments

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

1 Comment

when I use this I get this error "Argument type 'JSON' expected to be an instance of a class or class-constrained type"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.