Save json to CoreData as String and use the String to create array of objects

前端 未结 2 499
醉酒成梦
醉酒成梦 2021-02-03 16:12

I am creating an app for a radio station and I want to store \"show\" objects into an array. I use a webserver to supply json data to populate the array, but I want to store thi

2条回答
  •  被撕碎了的回忆
    2021-02-03 16:53

    Try this it's work for me

    // Convert JSON to String
    func jsonToString(json: AnyObject)->String{
        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
            return convertedString! // <-- here is ur string
    
        } catch let myJSONError {
            print(myJSONError)
        }
    
        return ""
    }
    
    // Convert JSON String to Dict
    func convertToDictionary(text: String) -> NSDictionary!{
        if let data = text.data(using: .utf8) {
            do {
    
                return try JSONSerialization.jsonObject(with: data, options: []) as? NSDictionary
            } catch {
                print(error.localizedDescription)
            }
        }
        return nil
    }
    

提交回复
热议问题