如果对象包含基于键的重复名称,则对json对象进行分组?

时间:2018-02-23 06:30:40

标签: ios swift3 collections swift4

我们正在使用如下的json对象数组:

[{
    "CompanyCode": "1",
    "MachineCode": null,
    "MachineName": null,
    "NoOfMeters": null,
    "ScheduleNo": "12028",
    "ScheduleDate": "17/2/2018 12:00:00 AM",
    "ScheduleUser": "sales",
    "CustomerCode": "0022100007",
    "DeliveryCode": "0",
    "SortOrder": "1",
    "JobRefNo": "",
    "CustomerName": "COLD STORAGE SUPERMARKETS ",
    "CustAddress1": "GIANT COMPLEX",
    "OutletName": "",
    "OutAddress1": "",
    "IsJobClosed": ""
}, {
    "CompanyCode": "1",
    "MachineCode": null,
    "MachineName": null,
    "NoOfMeters": null,
    "ScheduleNo": "12029",
    "ScheduleDate": "17/2/2018 12:00:00 AM",
    "ScheduleUser": "sales",
    "CustomerCode": "0022100008",
    "DeliveryCode": "0",
    "SortOrder": "1",
    "JobRefNo": "",
    "CustomerName": "COLD STORAGE WH - 21 TAMPINES ",
    "CustAddress1": "GIANT COMPLEX",
    "OutletName": "",
    "OutAddress1": "",
    "IsJobClosed": ""
}, {
    "CompanyCode": "1",
    "MachineCode": null,
    "MachineName": null,
    "NoOfMeters": null,
    "ScheduleNo": "12027",
    "ScheduleDate": "17/2/2018 12:00:00 AM",
    "ScheduleUser": "winapp",
    "CustomerCode": "0022100003",
    "DeliveryCode": "0",
    "SortOrder": "1",
    "JobRefNo": "",
    "CustomerName": "AVENZA PTE LTD ",
    "CustAddress1": "83 CLEMENCEAU AVE",
    "OutletName": "",
    "OutAddress1": "",
    "IsJobClosed": ""
}, {
    "CompanyCode": "1",
    "MachineCode": null,
    "MachineName": null,
    "NoOfMeters": null,
    "ScheduleNo": "12025",
    "ScheduleDate": "17/2/2018 12:00:00 AM",
    "ScheduleUser": "winapp",
    "CustomerCode": "0022100001",
    "DeliveryCode": "0",
    "SortOrder": "1",
    "JobRefNo": "",
    "CustomerName": "CASH ON DELIVERY (TO) ",
    "CustAddress1": "CASH ON DELIVERY",
    "OutletName": "",
    "OutAddress1": "",
    "IsJobClosed": ""
}, {
    "CompanyCode": "1",
    "MachineCode": null,
    "MachineName": null,
    "NoOfMeters": null,
    "ScheduleNo": "12026",
    "ScheduleDate": "17/2/2018 12:00:00 AM",
    "ScheduleUser": "winapp",
    "CustomerCode": "0022100002",
    "DeliveryCode": "0",
    "SortOrder": "1",
    "JobRefNo": "",
    "CustomerName": "DESPATCH - MT ",
    "CustAddress1": "DESPATCH",
    "OutletName": "",
    "OutAddress1": "",
    "IsJobClosed": ""
}]

我们希望将此阵列分组基于 ScheduleUser 键,如部分。

[
  "Sales":[
            {

            }
            {

            }

           ]
  "winapp":[
            {

                }
            {

                }

            {

            }

            ]
  ]

我们研究过swift 4 Here

中的分组

但是他们给出了一系列字符串,我们不知道如何处理json值。 如果有任何其他方式,请给我们解决方案。我们提到了以下Link

我们无法理解这一点。

从本地获取值

if let path = Bundle.main.path(forResource: "salesorder", ofType: "json") {
        do {
            let data = try Data(contentsOf: URL(fileURLWithPath: path), options: .alwaysMapped)
            do{
                let json =  try JSONSerialization.jsonObject(with: data, options: .allowFragments)
                let jsonDictionary =  json as? [[String:Any]]

                print(jsonDictionary!)

            }catch let error{
                print(error.localizedDescription)
            }
        } catch let error {
            print(error.localizedDescription)
        }
    } else {
        print("Invalid filename/path.")
    }

提前致谢..

2 个答案:

答案 0 :(得分:1)

更好的

使用分组方式

if let path = Bundle.main.path(forResource: "salesorder", ofType: "json") {
        do {
            let data = try Data(contentsOf: URL(fileURLWithPath: path), options: .alwaysMapped)
            do{
                let json =  try JSONSerialization.jsonObject(with: data, options: .allowFragments)
                if let jsonDictionary =  json as? [[String:Any]]{

                var grouped2 : [String:[[String:Any]]] = Dictionary(grouping: jsonDictionary, by: {$0["ScheduleUser"] as! String})
                debugPrint(grouped2)
                print(jsonDictionary)
                }

            }catch let error{
                print(error.localizedDescription)
            }
        } catch let error {
            print(error.localizedDescription)
        }
    } else {
        print("Invalid filename/path.")
    }

手动方式

if let path = Bundle.main.path(forResource: "salesorder", ofType: "json") {
            do {
                let data = try Data(contentsOf: URL(fileURLWithPath: path), options: .alwaysMapped)
                do{
                    let json =  try JSONSerialization.jsonObject(with: data, options: .allowFragments)
                    if let jsonDictionary =  json as? [[String:Any]]{

                        var grouped : [String:[[String:Any]]] = [:]
                        for dict in jsonDictionary {
                            let value = dict["ScheduleUser"] as! String
                            if(grouped[dict["ScheduleUser"] as! String] == nil){
                                grouped[value] = [dict]
                            }else{
                                grouped[value]?.append(dict)
                            }
                        }
                        debugPrint(grouped)
                    print(jsonDictionary)
                    }

                }catch let error{
                    print(error.localizedDescription)
                }
            } catch let error {
                print(error.localizedDescription)
            }
        } else {
            print("Invalid filename/path.")
        }

<强>日志

  

[“winapp”:[[“MachineName”:,“CustomerCode”:0022100003,   “JobRefNo”:,“OutAddress1”:,“SortOrder”:1,“IsJobClos​​ed”:,,   “CustAddress1”:83 CLEMENCEAU AVE,“OutletName”:,“MachineCode”:   ,“ScheduleDate”:17/2/2018 12:00:00 AM,“客户名称”:AVENZA   PTE LTD,“ScheduleNo”:12027,“NoOfMeters”:,“DeliveryCode”:   0,“ScheduleUser”:winapp,“CompanyCode”:1],[“MachineName”:,,   “CustomerCode”:0022100001,“JobRefNo”:,“OutAddress1”:,   “SortOrder”:1,“IsJobClos​​ed”:,“CustAddress1”:现金交付,   “OutletName”:,“MachineCode”:,“ScheduleDate”:17/2/2018   凌晨12:00:00,“客户名称”:现金交付(收货),“ScheduleNo”:   12025,“NoOfMeters”:,“DeliveryCode”:0,“ScheduleUser”:   winapp,“CompanyCode”:1],[“MachineName”:,“CustomerCode”:   0022100002,“JobRefNo”:,“OutAddress1”:,“SortOrder”:1,   “IsJobClos​​ed”:,“CustAddress1”:DESPATCH,“OutletName”:,   “MachineCode”:,“ScheduleDate”:17/2/2018 12:00:00 AM,   “客户名称”:DESPATCH - MT,“ScheduleNo”:12026,“NoOfMeters”:   ,“DeliveryCode”:0,“ScheduleUser”:winapp,“CompanyCode”:1]],   “sales”:[[“MachineName”:,“CustomerCode”:0022100007,   “JobRefNo”:,“OutAddress1”:,“SortOrder”:1,“IsJobClos​​ed”:,,   “CustAddress1”:GIANT COMPLEX,“OutletName”:,“MachineCode”:,   “ScheduleDate”:17/2/2018 12:00:00 AM,“客户名称”:冷藏   SUPERMARKETS,“ScheduleNo”:12028,“NoOfMeters”:,,   “DeliveryCode”:0,“ScheduleUser”:sales,“CompanyCode”:1],   [“MachineName”:,“CustomerCode”:0022100008,“JobRefNo”:,,   “OutAddress1”:,“SortOrder”:1,“IsJobClos​​ed”:,“CustAddress1”:   GIANT COMPLEX,“OutletName”:,“MachineCode”:,“ScheduleDate”:   17/2/2018 12:00:00 AM,“客户名称”:冷库存 - WH-21 TAMPINES,   “ScheduleNo”:12029,“NoOfMeters”:,“DeliveryCode”:0,   “ScheduleUser”:sales,“CompanyCode”:1]]]

答案 1 :(得分:1)

获取数组中的所有可能值 -

let arr = your data...
let posValues = arr.map { $0["ScheduleUser"] as? String }

现在为过滤数据创建一个字典 -

var newDict:[String:Any] = [:]

for aValue in posValues {

    let filteredDicts = arr.filter({ ($0.["ScheduleUser"] == aValue)})
    newDict[aValue] = filteredDicts
}