问题:
解决:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 |
import Foundation func toJson(obj : Any) -> String?{ do { let aa = toObj(obj:obj) let jsonData = try JSONSerialization.data(withJSONObject: aa, options: []) let jsonString = String.init(data: jsonData, encoding: .utf8) return jsonString } catch { print(error) return nil } } func toObj(obj : Any) -> Any{ if let a = obj as? [Any] { var a2 = [Any]() for e in a { let d = toObj(obj: e) a2.append(d) } return a2 }else if obj is Int || obj is String || obj is Bool || obj is Float || obj is Double || obj is NSNull { return obj } else { let dic = toDictionary(obj: obj); if dic.count > 0 { return dic }else {////optional none return obj } } } func toDictionary(obj : Any) -> [String: Any] { var dictionary = [String: Any]() let otherSelf = Mirror(reflecting: obj) for child in otherSelf.children { guard let key = child.label else { continue } let v = child.value dictionary[key] = toObj(obj:v) } return dictionary } extension Dictionary { func floatValue(_ name:Dictionary.Key) ->Float?{ var ret : Float? = nil if let n = self[name] as? NSNumber { ret = n.floatValue }else if let f = self[name] as? Float { ret = f } return ret } } |
参考: