简体   繁体   中英

How to convert JSON to String in ios Swift?

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?

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: NSUTF8StringEncoding) // the data will be converted to the string
            print(convertedString) // <-- here is ur string  

        } catch let myJSONError {
            print(myJSONError)
        }

    }

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

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

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

将 JSON 对象转换为字符串的一种简单方法是: 1. 首先创建一个 JSON 下标值,例如 jsonObject["fieldName"] 2. 使用 '.stringValue' 属性来检索实际的 String 等效项 (jsonObject["fieldName"] .stringValue)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM