本文介绍了如何在iOS Swift中将JSON转换为String?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是下面的Json输出的代码:

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

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

By printing jsonObject, I got this one.

我希望JSON采用以下格式.

And I want the JSON to be in the below format.

该怎么办?仅需要更改cartJsonData中的值.有人可以帮我解决这个问题吗?

How can it be done? Only the value in cartJsonData needs to be changed. Can someone help me on this to solve 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)
        }

    }

这篇关于如何在iOS Swift中将JSON转换为String?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 13:51