Monday, 15 July 2019

Convert Array, Dictionary into JSON in Swift :



Convert Dictionary into JSON in Swift :

From:  https://stackoverflow.com/questions/29625133/convert-dictionary-to-json-in-swift

let dic = ["2": "B", "1": "A", "3": "C"]
let encoder = JSONEncoder()
if let jsonData = try? encoder.encode(dic) {
    if let jsonString = String(data: jsonData, encoding: .utf8) {
        print(jsonString)
    }
}


Convert Array in to JSON in Swift

From :  https://riptutorial.com/ios/example/28692/convert-array-into-json-string

let array = [["prod_uniq" : "5cb5d3aecd4d9"], ["Quantity" : "500"], ["Amount" : "1000"]]
        
let jsonString = convertIntoJSONString(arrayObject: array)
print("jsonString - \(jsonString ?? "Empty JSON")")

        
func convertIntoJSONString(arrayObject: [Any]) -> String? {
        
        do {
            let jsonData: Data = try JSONSerialization.data(withJSONObject: arrayObject, options: [])
            if  let jsonString = NSString(data: jsonData, encoding: String.Encoding.utf8.rawValue) {
                return jsonString as String
            }
            
        } catch let error as NSError {
            print("Array convertIntoJSON - \(error.description)")
        }
        return nil
    }


No comments:

Post a Comment

Difference between == and ===

Difference between == and === https://stackoverflow.com/questions/24002819/difference-between-and == operator checks if their ...