在 Playground 上测试运行
选项 1:使用 Dictionary 检查
func convertToDictionary(json: String) -> [String: Any]? {
if let data = json.data(using: .utf8) {
do {
return try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]
} catch {
print(error.localizedDescription)
}
}
return nil
}
func getNonEmptyCount(dict: [String: Any]?) -> Int {
return dict?.filter({
if let value = $0.value as? String {
return !value.isEmpty
} else if let value = $0.value as? Int {
return value > 0
} else {
return false
}
}).count ?? 0
}
let json = """
{
"postID": 325,
"postName": "Test1",
"postDetail": "Test1",
"postDesc": "",
}
"""
getNonEmptyCount(dict: convertToDictionary(json: json))
选项 2:使用镜像检查
let json = """
{
"postID": 325,
"postName": "Test1",
"postDetail": "Test1",
"postDesc": "",
}
"""
func getNonEmptyCount(json: String) -> Int {
let model = try! JSONDecoder().decode(Post.self, from: json.data(using: .utf8)!)
let mirror = Mirror(reflecting: model)
return mirror.children.filter {
if let value = $0.value as? String {
return !value.isEmpty
} else if let value = $0.value as? Int {
return value > 0
} else {
return false
}
}.count
}
print(getNonEmptyCount(json: json))