简体   繁体   English

解析json并使用tableview显示

[英]Parse json and show with tableview

I'm new to Swift, and not good at manipulating json and hash. 我是Swift的新手,也不擅长处理json和hash。

Here's my JSON [Array of Users] 这是我的JSON [用户数组]

[
{"name": "mary", "age": 24, "detail": "i love ..."},
{"name": "mark", "age": 28, "detail": "i love ..."}
]

I want to show each user's name first and then their age 我想先显示每个用户的名字,然后显示他们的age

And If you click there name or age, it will show the detail 如果您单击此处的名称或年龄,它将显示detail

I only know how to iterate a array and puts the value on the cell. 我只知道如何迭代数组并将值放在单元格上。

Like this way, but now knowing how to display tablecells with a dictionary 像这样,但是现在知道如何用字典显示表格单元

cell.textLabel.text = self.items[indexPath.row]

How could I know which key should I use in each loop ? 如何知道每个循环中应使用哪个key

func tableView(invoice: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

How could I know this time, I should use the name , and next time I should use age to show my cell? 这次我怎么知道我应该使用name ,而下次我应该使用age来显示我的细胞?

在此处输入图片说明

Since your original JSON is an array, you can parse the JSON elements in a dictionary and then use it in your cell. 由于原始JSON是数组,因此您可以解析字典中的JSON元素,然后在单元格中使用它。

func parseJSONArray(jsonData: NSData) -> Array<NSDictionary>{
    var error: NSError?
    var usersDictionary = NSJSONSerialization.JSONObjectWithData(jsonData, options: NSJSONReadingOptions.MutableContainers, error: &error) as Array<NSDictionary>
    return usersDictionary
}

Then you can use this usersDictionary to get your users info: 然后,您可以使用此usersDictionary获取您的用户信息:

cell.textlabel.text = usersDictionary[indexPath.row].valueForKey("name")

For the logic of key decision, try something like below: 有关关键决策的逻辑,请尝试以下操作:

var index = indexPath.row/2;
var key = indexPath.row%2;

if (key == 0) { //show the name cell
    cell.textlabel.text = usersDictionary[index].valueForKey("name")
} else { //show the age cell
    cell.textlabel.text = "Age " + usersDictionary[index].valueForKey("age")
}

Similar logic for cell font style and color can be used by you. 您可以使用类似的单元字体样式和颜色的逻辑。 Its not very complex. 它不是很复杂。 Just make sure to have number of rows as twice the json array size (1 cell for each key) and also proper logic for cell selected method. 只需确保行数是json数组大小的两倍(每个键1个单元格),并为单元格选择的方法提供适当的逻辑即可。

try this code, because name is show in even cell, age show in odd 尝试使用此代码,因为名称在偶数单元格中显示,年龄在奇数中显示

var index = indexPath.row/2;
var isAgeCell = indexPath.row%2
if (isAgeCell == 0) {
    cell.textLabel.text = self.items[index]["name"]
}
else {
    cell.textLabel.text = self.items[index]["age"]
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM