【问题标题】:Issues while printing json array in object on tableview在 tableview 上的对象中打印 json 数组时出现问题
【发布时间】:2018-08-09 11:40:35
【问题描述】:

我正在调用 api,我得到了正确的响应,但我不明白如何打印一个对象数组,就像我的响应一样

回应

{
    "success": "1",
    "data": [
        {
            "month": 0
        },
        {
            "month": 0
        },
        {
            "month": 0
        },
        {
            "month": 0
        },
        {
            "month": 0
        },
        {
            "month": 0
        },
        {
            "month": 0
        },
        {
            "month": 3
        },
        {
            "month": 0
        },
        {
            "month": 0
        },
        {
            "month": 0
        },
        {
            "month": 0
        }
    ],
    "like_data": [
        {
            "like": 0
        },
        {
            "like": 0
        },
        {
            "like": 0
        },
        {
            "like": 0
        },
        {
            "like": 0
        },
        {
            "like": 0
        },
        {
            "like": 0
        },
        {
            "like": 6
        },
        {
            "like": 0
        },
        {
            "like": 0
        },
        {
            "like": 0
        },
        {
            "like": 0
        }
    ],
    "cmnt_data": [
        {
            "cmnt": 0
        },
        {
            "cmnt": 0
        },
        {
            "cmnt": 0
        },
        {
            "cmnt": 0
        },
        {
            "cmnt": 0
        },
        {
            "cmnt": 0
        },
        {
            "cmnt": 0
        },
        {
            "cmnt": 1
        },
        {
            "cmnt": 0
        },
        {
            "cmnt": 0
        },
        {
            "cmnt": 0
        },
        {
            "cmnt": 0
        }
    ]
}

所以我想打印我试过的 like_data 和 cmnt_data 让我给你看我的代码

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
       let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! InstaAnalyticsTableViewCell
       let month = searchlist[indexPath.row]["month"]! as? Int
        print(month!)
        let optionalvalue = month
        if let noLongerOptional = optionalvalue {
            print("\(noLongerOptional) no its not! ahah")
            cell.lblMonthCount.text = "\(noLongerOptional)" as? String
        }

         let instaResponse = searchlist[indexPath.row]["like_data"] as! [String:Any]
         let likes = instaResponse["like"] as! Int
         cell.lblLikeCount.text = "\(likes)"
        //cell.lblMonthCount.text = "\(month)"
        return cell
    }

我正在尝试如上所述,但我没有得到我做错的地方请帮助我解决这个问题,还需要一个帮助我想将所有数据显示为条形图或折线字符所以请任何人帮助我

看到这里我是这样调用api的,所以我必须写哪个响应

Alamofire.request(instaPostAnalytics, method: .post, parameters: userprofile).responseJSON
                {
                    response in

                    print(response)
                    let result = response.result
                    print(result)
                    let monthArray = yourResponse["data"] as? [[String:Int]] ?? []
                    let likeArray = yourResponse["like_data"] as? [[String:Int]] ?? []
                    let cmntArray = yourResponse["cmnt_data"] as? [[String:Int]] ?? []
                    //As of all have equal object loop like this
                    for i in 0..<min(monthArray.count, likeArray.count, cmntArray.count) {
                        let month = monthArray[i]["month"] ?? 0
                        let like = likeArray[i]["like"] ?? 0
                        let cmnt = cmntArray[i]["cmnt"] ?? 0
                        datas.append(Data(month: month, like: like, cmnt: cmnt))
                    }
                    //Now reload the tableView
                    self.yourTableView.reloadData()
//                    if let dict = result.value as? Dictionary<String,AnyObject>{
//                        if let categorylist = dict["data"]{
//                            self.searchlist = categorylist as! [AnyObject]
//                            self.tblInstalytics.reloadData()
//                    }
//                }
            }

正如我昨天所说,我无法在图表上显示数据,这是我的代码

代码

        let data = response.result
        if let dict = data.value as? Dictionary<String,AnyObject>{
            if let categorylist = dict["data"]{
                self.searchlist = categorylist as! [AnyObject]

                for item in self.searchlist{
                    let value = item["month"]
                    guard let value_chart = value else {
                        continue
                    }
                    let optionalvalue = value_chart
                    if let noLongerOptional = optionalvalue {
                        print("\(noLongerOptional)")
                        let chartConfig = BarsChartConfig(valsAxisConfig: ChartAxisConfig(from: 0, to: 800, by: 100))
                        let frame = CGRect(x: 0, y: 20, width: self.view.frame.width, height: 232 )
                        let chart = BarsChart(frame: frame,
                                              chartConfig: chartConfig,
                                              xTitle: "Months",
                                              yTitle: "Count",
                                              bars: [
                                                ("Jan", noLongerOptional as! Double),
                                                ("Feb", noLongerOptional as! Double),
                                                ("Mar", noLongerOptional as! Double),
                                                ("Apr", noLongerOptional as! Double),
                                                ("May", noLongerOptional as! Double),
                                                ("Jun", noLongerOptional as! Double),
                                                ("July",noLongerOptional as! Double),
                                                ("Aug", noLongerOptional as! Double),
                                                ("Sep", noLongerOptional as! Double),
                                                ("Oct", noLongerOptional as! Double),
                                                ("Nov", noLongerOptional as! Double),
                                                ("Dec", noLongerOptional as! Double)
                            ],
                                              color: UIColor.red,
                                              barWidth: 15
                        )
                        self.view.addSubview(chart.view)
                        self.chartView = chart
                    }
                }
            }

但我无法显示,也无法理解如何在图表中显示 likeData 和 cmnt 数据

请帮我解决这个问题

【问题讨论】:

  • 请解释一下,我无法理解
  • 你对那个糟糕的 JSON 结构负责吗?如果不是,则责怪服务的所有者。一组字典分别只包含一个键,效率极低。

标签: ios json swift uitableview alamofire


【解决方案1】:

而不是在您的JSON 中拥有 3 个不同的数组,您应该拥有一个数组,其中所有值都包含在它的单个对象中。

{
    "success": "1",
    "data": [ {
        "month": 0,
        "like": 0,
        "cmnt": 1
    },
    ...
    ]
}

到目前为止,对于您当前的 JSON 响应,您可以做的是创建一个 structclass 数组并将其用作 tableView 的数据源。

struct Post {
    var month: Int
    var like: Int
    var cmnt: Int
}

现在在您的控制器中声明 Post 数组并将其与您的 tableView 方法一起使用。

var datas = [Post]()

//Initialize datas array like this when you get `JSON`
let result = response.result.value as? [String : Any] ?? [:]
let monthArray = result["data"] as? [[String:Int]] ?? []
let likeArray = result["like_data"] as? [[String:Int]] ?? []
let cmntArray = result["cmnt_data"] as? [[String:Int]] ?? []
//As of all have equal object loop like this
for i in 0..<min(monthArray.count, likeArray.count, cmntArray.count) {
    let month = monthArray[i]["month"] ?? 0
    let like = likeArray[i]["like"] ?? 0
    let cmnt = cmntArray[i]["cmnt"] ?? 0
    datas.append(Post(month: month, like: like, cmnt: cmnt))
}
//Now reload the tableView
self.yourTableView.reloadData()

现在只需像这样更改UITableViewDataSource 方法。

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return datas.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! InstaAnalyticsTableViewCell
    let data = datas[indexPath.row]
    cell.lblMonthCount.text = String(data.month)
    cell.lblLikeCount.text = String(data.like)
    cell.lblCmntCount.text = String(data.cmnt)
    return cell        
}

【讨论】:

  • @Nirav 请检查我的新问题
【解决方案2】:
//first take 3 dataArray for taking values from the response 

var likeArr = fullresponce["like_data"] as [[String:Anyobject]]
var commentArr = fullresponce["cmnt_data"] as [[String:Anyobject]]

var like = (likeArr[indexPath.row] as Dictionary)["like"]! as? Int

var cmnt = (commentArr[indexPath.row] as Dictionary)["cmnt"]! as? Int

【讨论】:

  • 这里我把 fullresponse 作为搜索列表可以吗? var likeArr = fullresponce["like_data"] as [[String:Anyobject]]
  • 让 instaResponse = searchlist[indexPath.row]["like_data"] as! [String:Any] 让 likes = instaResponse["like"] as! string cell.lblLikeCount.text = "(喜欢)"
猜你喜欢
  • 2021-01-22
  • 1970-01-01
  • 1970-01-01
  • 2014-10-28
  • 2022-11-26
  • 1970-01-01
  • 2019-06-17
  • 1970-01-01
  • 2015-01-13
相关资源
最近更新 更多