How to convert JSON to String in ios Swift?

后端 未结 7 1780
孤独总比滥情好
孤独总比滥情好 2020-12-15 16:30

Here is the code for the below Json output:

let params : [[String : AnyObject]]  = [[\"name\" : \"action\", \"value\" : \"pay\" ],[\"name\" : \"cartJsonData\         


        
7条回答
  •  旧巷少年郎
    2020-12-15 16:42

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

提交回复
热议问题