使用Decodable解析JSON

时间:2018-07-12 22:50:18

标签: json swift parsing decodable

我很难弄清楚如何组合相似的json结果,以便在搜索API时,搜索结果仅显示一次特定的药物名称。我也遇到了同样的问题。当选择药物时,由于药物具有不同的包装代码(需要用于确定药物包装的覆盖范围),因此多行填充的强度相同。有任何想法吗?我不确定是否应该以其他方式解析它。

以下是操场中JSON的示例:

let json = """
{
"meta": {
  "total": 406
},
"drugs": [
{
   "id": "12547-0204",
   "active_ingredient_strength": "10mg",
   "proprietary_name": "Zyrtec",
   "non_proprietary_name": "Zyrtec"
   "drug_package_ids": [
    "12547-0204-30",
    "12547-0204-32",
    "12547-0204-36"
  ]
   },

{
   "id": "52959-0482",
   "active_ingredient_strength": "10mg",
   "proprietary_name": "Zyrtec",
   "non_proprietary_name": "Zyrtec"
   "drug_package_ids": [
    "52959-0482-01",
    "52959-0482-07",
    "52959-0482-10",
    "52959-0482-15",
    "52959-0482-30"
  ]
   },
{ 
   "id": "54868-5879",
   "active_ingredient_strength": "5; 120mg/1; mg/1",
   "proprietary_name": "ZYRTEC",
   "non_proprietary_name": "Cetirizine Hydrochloride and Pseudoephedrine      
   Hydrochloride",
   "drug_package_ids": [
    "54868-5879-0",
    "54868-5879-00",
    "54868-5879-00"
     ]
   }
  ]
}""".data(using: .utf8)!

struct DrugSearchResponse: Codable {
    let meta: Meta
    let drugs: [Drugs]

    struct Meta: Codable {
        let total: Int
    }
    struct Drugs: Codable {
        let id: String
        let active_ingredient_strength: String
        let proprietary_name: String
        let non_proprietary_name: String
    }
}

let decoder = JSONDecoder()
let results = try! decoder.decode(DrugSearchResponse.self, from: json)
let drugs = results.drugs
for name in drugs {
    print(name.proprietary_name)
}

以下是搜索结果的屏幕截图,仅供参考:

1 个答案:

答案 0 :(得分:0)

您可以过滤自定义数组的内容,并根据任何属性删除重复的有价物品。

例如这会删除除第一个专利以外的所有具有相同专有名称的药物

let result: [Drugs] = []
result.append(contentsOf: results.drugs.filter { item in
    !result.contains(where: { $0.proprietary_name == item.proprietary_name })
})