如何在ios Swift中将JSON转换为String?

时间:2016-04-02 07:36:15

标签: ios json swift

以下是Json输出的代码:

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

通过打印jsonObject,我得到了这个。

  

[{" value":" pay"," name":" action" },{" value":{" rows":[{   "价格":" 1","数量":" 1","费用":" 1& #34;,"货币":" INR",   " itemId":" DN001"," title":"为SMSF印度捐款 - 普通基金"   }," total":1}," name":" cartJsonData" },{"价值":" Chennai",   " name":" center" },{" value":" 503"," name":" flatNumber" },{   "价值":"","名称":" panNumber" },{" name":" payWith" },{"价值":   "每月","名称":"提醒频率" },{" name":" shipToAddr1" },{   " name":" shipToAddr2" },{" name":" shipToCity" },{"价值":"印度",   " name":" shipToCountryName" },{" value":" 01034_186893@gmail.com",   " name":" shipToEmail" },{" value":" 4480101010"," name":   " shipToFirstName" },{" name":" shipToLastName" },{"价值":   " 4480101010"," name":" shipToPhone" },{" name":" shipToState" },{   " name":" shipToZip" },{" value":" null"," name":" userId" },{   "价值":" IN","名称":" shipToCountry" }]

我希望JSON采用以下格式。

  

[{“name”:“action”,“value”:“pay”},{“name”:“cartJsonData”,   “值”:   “{\”total \“:1,\”rows \“:[{\”itemId \“:\”DN002 \“,\”title \“:\”捐款   SMSF印度 - 将军   基金\”,\”数量\”:\” 100 \”,\”货币\”:\” INR \”,\”价格\”:\” 1 \”,\”成本\”:\” 100 \ “}]}”   },{“name”:“center”,“value”:“Chennai”},{“name”:“flatNumber”,   “value”:“”},{“name”:“panNumber”,“value”:“ASSDDBBDJD”},{   “name”:“payWith”},{“name”:“reminderFrequency”,“value”:“每月”   },{“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”}]

怎么做?只需要更改cartJsonData中的值。有人可以帮我解决这个问题吗?

7 个答案:

答案 0 :(得分:33)

试试这个。

status_id

答案 1 :(得分:8)

Swift (截至2018年7月10日)

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

}

答案 2 :(得分:6)

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

用法

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

答案 3 :(得分:1)

使用新的基于Encodable的API,您可以使用String(init:encoding)初始化器获取JSON文件的字符串版本。我在Playground中运行了这个,最后一个打印语句给了我

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

似乎格式详细使用了最少数量的字符。

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

答案 4 :(得分:1)

  • Swift 4.x
  • xcode 10.x
  

如果您使用的是Swifty JSON

var stringfyJSOn  = yourJSON.description

答案 5 :(得分:0)

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

答案 6 :(得分:0)

Xcode 11,将String转换为NSString对我有用。

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