分组JSON内容

时间:2019-04-17 11:43:10

标签: json swift group-by

这是我的json:

[
  {
    "category" : {
      "id" : 1,
      "text" : "cat1"
    },
    "id" : 1,
    "title" : "book1"
  },{
    "category" : {
      "id" : 2,
      "text" : "cat2"
    },
    "id" : 2,
    "title" : "book2"
  },{
    "category" : {
      "id" : 1,
      "text" : "cat1"
    },
    "id" : 3,
    "title" : "book3"
  }
]

如何按类别分组?我想在不同的 collectionView

中使用它们

提前谢谢

enter image description here

3 个答案:

答案 0 :(得分:2)

如下定义您的JSON可编码类。

typealias Result = [ResultElement]

struct ResultElement: Codable {
    let category: Category
    let id: Int
    let title: String
}

struct Category: Codable {
    let id: Int
    let text: String
}

现在,在使用JSONDecoder进行JSON解析之后,对Result数组进行迭代,并通过等号运算符比较Category结构并将其分组。由于默认情况下,类别结构中的IntString符合Equatable协议,因此也可以使用Equatable协议来比较类别结构。

答案 1 :(得分:1)

您可以尝试

        let str = """
[
{
"category" : {
"id" : 1,
"text" : "cat1"
},
"id" : 1,
"title" : "book1"
},{
"category" : {
"id" : 2,
"text" : "cat2"
},
"id" : 2,
"title" : "book2"
},{
"category" : {
"id" : 1,
"text" : "cat1"
},
"id" : 3,
"title" : "book3"
}
]


"""

        do {

            let res = try JSONDecoder().decode([Root].self, from: Data(str.utf8))

            print(res)

            let dic = Dictionary(grouping: res, by: { $0.category.text})

            print(dic) // this dictionary is your new data source key is title of section value is sections rows 
        }
        catch {
            print(error)
        }

struct Root: Codable {
    let category: Category
    let id: Int
    let title: String
}

struct Category: Codable {
    let id: Int
    let text: String
}

答案 2 :(得分:1)

  1. 创建结构

    //MARK: - MyData
    public struct MyData {
    
        public var category : Category
        public var id : Int
        public var title : String
    
    }
    
    //MARK: - Category
    public struct Category {
    
        public var id : Int
        public var text : String
    
    }
    
  2. 创建模型

    func createData () -> [MyData] {
        let c1 = Category.init(id: 1, text: "Cat1")
        let d1 = MyData.init(category: c1, id: 1, title: "Book1")
        let c2 = Category.init(id: 2, text: "Cat2")
        let d2 = MyData.init(category: c2, id: 2, title: "Book2")
        let c3 = Category.init(id: 1, text: "Cat1")
        let d3 = MyData.init(category: c3, id: 3, title: "Book3")
    
        return [d1, d2, d3]
    
    }
    
  3. 对数据进行分组

        let ungroupedData = createData()
        print("Ungrouped\n")
        print(ungroupedData)
        let groupedData = Dictionary(grouping: ungroupedData, by: {$0.category.text})
        print("\nGrouped\n")
        print(groupedData)
    
        groupedData["Cat1"] // get cat1 array list