I am trying to load the values from the JSON to the tableview. Here is my code, I dont know what am I missing? It shows me a list of blank cells but not any values.
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
var tableView: UITableView!
let baseURL = “<url>”
var items = [UserObject]()
override func viewDidLoad() {
super.viewDidLoad()
let frame:CGRect = CGRect(x: 0, y: 100, width: self.view.frame.width, height: self.view.frame.height-100)
self.tableView = UITableView(frame: frame)
self.tableView.dataSource = self
self.tableView.delegate = self
self.view.addSubview(self.tableView)
getJSON()
dispatch_async(dispatch_get_main_queue(),{
self.tableView.reloadData()
})
}
//5 rows
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
print("count /(self.items.count)")
return self.items.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier("CELL")
if cell == nil {
cell = UITableViewCell(style: UITableViewCellStyle.Value1, reuseIdentifier: "CELL")
}
let user = self.items[indexPath.row]
print(self.items)
cell!.textLabel?.text = user.name
return cell!
}
func getJSON() {
let url = NSURL(string: baseURL)
print(url)
let request = NSURLRequest(URL: url!)
let session = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration())
let task = session.dataTaskWithRequest(request) { (data, response, error) -> Void in
if error == nil {
let swiftyJSON = JSON(data: data!)
let results = swiftyJSON.arrayValue
for entry in results {
self.items.append(UserObject(json: entry))
}
} else {
print("error \(error)")
}
}
task.resume()
}
}
Please note, print("count /(self.items.count)") returns 4 which is correct but
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
//function does not show any print statements.
}
You should call the tableview's reloadData func after your async request is finished.
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
var tableView: UITableView!
let baseURL = “<url>”
var items = [UserObject]()
override func viewDidLoad() {
super.viewDidLoad()
let frame:CGRect = CGRect(x: 0, y: 100, width: self.view.frame.width, height: self.view.frame.height-100)
self.tableView = UITableView(frame: frame)
self.tableView.dataSource = self
self.tableView.delegate = self
self.view.addSubview(self.tableView)
getJSON()
}
//5 rows
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
print("count /(self.items.count)")
return self.items.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier("CELL")
if cell == nil {
cell = UITableViewCell(style: UITableViewCellStyle.Value1, reuseIdentifier: "CELL")
}
let user = self.items[indexPath.row]
print(self.items)
cell!.textLabel?.text = user.name
cell!.detailTextLabel?.text = user.date // UPDATE
return cell!
}
func getJSON() {
let url = NSURL(string: baseURL)
print(url)
let request = NSURLRequest(URL: url!)
let session = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration())
let task = session.dataTaskWithRequest(request) { (data, response, error) -> Void in
if error == nil {
let swiftyJSON = JSON(data: data!)
let results = swiftyJSON.arrayValue
for entry in results {
self.items.append(UserObject(json: entry))
}
dispatch_async(dispatch_get_main_queue(),{
self.tableView.reloadData()
})
} else {
print("error \(error)")
}
}
task.resume()
}
}
Your Get json function should be like,
func getJSON() {
let url = NSURL(string: baseURL)
print(url)
let request = NSURLRequest(URL: url!)
let session = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration())
let task = session.dataTaskWithRequest(request) { (data, response, error) -> Void in
if error == nil {
let swiftyJSON = JSON(data: data!)
let results = swiftyJSON.arrayValue
for entry in results {
self.items.append(UserObject(json: entry))
}
dispatch_async(dispatch_get_main_queue(),{
self.tableView.reloadData()
})
} else {
print("error \(error)")
}
}
task.resume()
}
and remove
dispatch_async(dispatch_get_main_queue(),{
self.tableView.reloadData()
})
from view didload. I have just put code of reloading table view in completion handler of web service call.
Related
I'm relatively new to swift, and I'm trying to have a view that when it loads it will display some info on my tableView, then in the same view I have a textfield and a button
I want that the button performes an action that fetchs data from my server and updates my tableView
The problem is that the table is not being updated. How can I get the table to be updated?
CODE:
override func viewDidLoad() {
super.viewDidLoad()
tableView.rowHeight = 80;
tableView.tableFooterView = UIView();
self.url = URL(string: "http://xxxxxxxx.com/xxxxx/api/produtos/listagem/favoritos/\(userID)");
downloadJson(_url: url!);
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return produtos.count;
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "ProdutoCell1") as? ProdutoCell else{
return UITableViewCell()
}
cell.lbl_nome_json.text = produtos[indexPath.row].nome;
cell.lbl_categoria_json.text = produtos[indexPath.row].categoria;
cell.lbl_loja_json.text = produtos[indexPath.row].loja
//= produtos[indexPath.row].categoria;
// cell.lbl_loja.text = produtos[indexPath.row].loja;
if let imageURL = URL(string: "http://xxxxxxxxxx.com/myslim/api/"+produtos[indexPath.row].url){
DispatchQueue.global().async {
let data = try? Data(contentsOf: imageURL);
if let data = data{
let image = UIImage(data: data);
DispatchQueue.main.async {
cell.imgView_json.image = image;
}
}
}
}
return cell;
}
ACTION:
#IBAction func btn_search(_ sender: Any) {
if self.txt_search.text == "" {
let alert = UIAlertController(title:"Alert",message: "Insira algo para pesquisar",preferredStyle: UIAlertController.Style.alert)
alert.addAction(UIAlertAction(title: "Click", style: UIAlertAction.Style.default, handler: nil))
self.present(alert,animated: true,completion: nil)
}else{
var pesquisa = String();
pesquisa = self.txt_search.text!;
let url2 = URL(string: "http://xxxxxxxx.com/xxxxxx/api/produtos/listagem/favoritos/\(pesquisa)/\(self.userID)");
downloadJson(_url: url2!);
}
func downloadJson(_url: URL){
guard let downloadURL = url else {return}
URLSession.shared.dataTask(with: downloadURL){data, urlResponse, error in
guard let data = data, error == nil, urlResponse != nil else{
print("algo está mal");
return;
}
do{
let decoder = JSONDecoder();
let downloadedProdutos = try decoder.decode([ProdutoModel].self, from: data);
self.produtos = downloadedProdutos
print(downloadedProdutos);
DispatchQueue.main.async {
self.tableView.reloadData();
print("reload");
}
}catch{
print("algo mal depois do download")
}
}.resume();
}
EDIT
I added some print to see how many object were being returned on my downloadedProdutos variable, on the downloadJson() function.
And at the viewdidload I get 2 object, its normal because I only have 2 Products, but when the action is done I still get 2 object although I should get only 1 object
You need to set tableView.dataSource = self in viewWillAppear and it looks you missed func numberOfSections() -> Int method.
Add UITableViewDataSource like this
class YourViewController: UIViewController, UITableViewDataSource and it will recommend you required methods
I can't figure out why the cells don't return with data.
I can parse normally using the Decodable, which means that is working.
I've been trying all the methods I find without success.
struct MuscleGroup: Decodable {
let ExcerciseID: String
let description: String
let excerciseName: String
let muscleGroup: String
}
class ExerciseListViewController: UITableViewController {
var muscleGroup = [MuscleGroup]()
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return muscleGroup.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "ExerciseList", for: indexPath) as! ExcerciseList
let muscle = muscleGroup[indexPath.row]
cell.textLabel!.text = muscle.excerciseName
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print(self.muscleGroup[indexPath.row])
tableView.deselectRow(at: indexPath, animated: true)
}
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.dataSource = self
self.tableView.delegate = self
getJson()
}
func getJson(){
guard let url = URL(string: "https://jsonurl") else { return }
let session = URLSession.shared
session.dataTask(with: url) { (data, response, error) in
if let response = response {
print(response)
}
if let data = data {
print(data)
do {
let muscles = try JSONDecoder().decode([MuscleGroup].self, from: data)
for muscle in muscles {
let muscleGroup = muscle.excerciseName
print(muscleGroup)
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
} catch {
print(error)
}
}
}.resume()
}
If I change the var muscleGroup = String to ["Chest", "Back", "Abdominals","Arms", "Legs"] it returns correctly.
Also, the print result on the console returns all the data that needs to be on the Table View.
What am I doing wrong?
As you probably want to use the entire struct
Replace
var muscleGroup = [String]()
with
var muscleGroups = [MuscleGroup]()
Replace
let muscles = try JSONDecoder().decode([MuscleGroup].self, from: data)
for muscle in muscles {
let muscleGroup = muscle.excerciseName
print(muscleGroup)
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
with
self.muscleGroups = try JSONDecoder().decode([MuscleGroup].self, from: data)
DispatchQueue.main.async {
self.tableView.reloadData()
}
Replace
cell.textLabel?.text = self.muscleGroup[indexPath.row]
with
cell.textLabel?.text = self.muscleGroups[indexPath.row].muscleGroup
In your getJson function this line
let muscleGroup = muscle.excerciseName
is creating a new local variable called muscleGroup, change the line to be
self.muscleGroup.append(muscle.excerciseName)
i.e. get rid of the let and append the value to the main array variable
Also move the
DispatchQueue.main.async {
self.tableView.reloadData()
}
to be outside of the for loop of muscles as you are forcing the table to reload for each entry rather than when you are finished
I want to pull to refresh for my RSS feed news app. I using navigation controller and table view controller. How should I do on Table View Controller? What should we add? My code is here.
class TableviewController: UITableViewController {
var items : Array<Item> = []
var entries : Array<Entry> = []
override func viewDidLoad() {
super.viewDidLoad()
loadRSS()
loadAtom()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "ItemCell", for: indexPath)
let item:Item = self.items[indexPath.row]
cell.textLabel?.text = item.title
cell.detailTextLabel?.text = self.pubDateStringFromDate(item.pubDate! as Date)
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let item = self.items[indexPath.row]
let url:URL = URL(string: item.link!)!
let safariViewController = SFSafariViewController(url: url, entersReaderIfAvailable: true)
present(safariViewController, animated: true, completion: nil)
}
func loadRSS() {
let feedUrlString:String = "websiteurl"
Alamofire.request(feedUrlString).response { response in
if let data = response.data, let _ = String(data: data, encoding: .utf8) {
TIFeedParser.parseRSS(xmlData: data as NSData, completionHandler: {(isSuccess, channel, error) -> Void in
if (isSuccess) {
self.items = channel!.items!
self.tableView.reloadData()
}
if (response.error != nil) {
print((response.error?.localizedDescription)! as String)
}
})
}
}
}
func loadAtom() {
let feedUrlString:String = "websiteurl"
Alamofire.request(feedUrlString).response { response in
if let data = response.data, let _ = String(data: data, encoding: .utf8) {
TIFeedParser.parseAtom(xmlData: data as NSData, completionHandler: {(isSuccess, feed, error) -> Void in
if (isSuccess) {
self.entries = feed!.entries!
self.tableView.reloadData()
}
if (error != nil) {
print((error?.localizedDescription)! as String)
}
})
}
}
}
func pubDateStringFromDate(_ pubDate:Date)->String {
let format = DateFormatter()
format.dateFormat = "yyyy/M/d HH:mm"
let pubDateString = format.string(from: pubDate)
return pubDateString
}
}
1) Declare an property of type UIRefreshControl as:
var refreshControl = UIRefreshControl()
2) In viewDidLoad()method add this refreshControl to your table view as:
self.refreshControl.addTarget(self, action: #selector(loadRSS), for: .valueChanged)
if #available(iOS 10, *){
self.tableView.refreshControl = self.refreshControl
}else{
self.tableView.addSubview(self.refreshControl)
}
Declare a property refreshControl in your TableViewController as
var refreshControl:UIRefreshControl?
The in viewDidLoad() function add the following code
refreshControl?.addTarget(self, action: #selector(loadRSS), for: .valueChanged)
self.tableView.addSubview(refreshControl!)
Update your loadRSS() function as
func loadRSS() {
let feedUrlString:String = "websiteurl"
Alamofire.request(feedUrlString).response { response in
self.refreshControl?.endRefreshing(
if let data = response.data, let _ = String(data: data, encoding: .utf8) {
TIFeedParser.parseRSS(xmlData: data as NSData, completionHandler: {(isSuccess, channel, error) -> Void in
if (isSuccess) {
self.items = channel!.items!
self.tableView.reloadData()
}
if (response.error != nil) {
print((response.error?.localizedDescription)! as String)
}
})
}
}
}
Please refer following code , as i have added pull to refresh control on your code.
class TableviewController: UITableViewController {
var items : Array<Item> = []
var entries : Array<Entry> = []
var pullToFrefreshNews:UIRefreshControl!
override func viewDidLoad() {
super.viewDidLoad()
loadRSS()
loadAtom()
self.addPulltoRefrehs()
}
func addPulltoRefrehs() {
self.pullToFrefreshNews = UIRefreshControl()
self.pullToFrefreshNews.addTarget(self, action: #selector(TableviewController.loadRSS), for: UIControlEvents.valueChanged)
self.newsTableVU.addSubview(pullToFrefreshNews)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "ItemCell", for: indexPath)
let item:Item = self.items[indexPath.row]
cell.textLabel?.text = item.title
cell.detailTextLabel?.text = self.pubDateStringFromDate(item.pubDate! as Date)
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let item = self.items[indexPath.row]
let url:URL = URL(string: item.link!)!
let safariViewController = SFSafariViewController(url: url, entersReaderIfAvailable: true)
present(safariViewController, animated: true, completion: nil)
}
func loadRSS() {
let feedUrlString:String = "websiteurl"
Alamofire.request(feedUrlString).response { response in
if let data = response.data, let _ = String(data: data, encoding: .utf8) {
TIFeedParser.parseRSS(xmlData: data as NSData, completionHandler: {(isSuccess, channel, error) -> Void in
if (isSuccess) {
self.items = channel!.items!
self.tableView.reloadData()
}
if (response.error != nil) {
print((response.error?.localizedDescription)! as String)
}
})
}
}
}
func loadAtom() {
let feedUrlString:String = "websiteurl"
Alamofire.request(feedUrlString).response { response in
if let data = response.data, let _ = String(data: data, encoding: .utf8) {
TIFeedParser.parseAtom(xmlData: data as NSData, completionHandler: {(isSuccess, feed, error) -> Void in
if (isSuccess) {
self.entries = feed!.entries!
self.tableView.reloadData()
}
if (error != nil) {
print((error?.localizedDescription)! as String)
}
})
}
}
}
func pubDateStringFromDate(_ pubDate:Date)->String {
let format = DateFormatter()
format.dateFormat = "yyyy/M/d HH:mm"
let pubDateString = format.string(from: pubDate)
return pubDateString
}
}
I am new to Swift, and am trying to create a table that reads JSON data from my website. I followed some tutorials, and was able to get my code to work with a table controller. Now I'm trying to use a view controller with a table view inside, so I can have more customization. My problem is, I can't get the data to actually show up when I try to use my new code.
This is what I have in my viewController.swift:
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var tableView: UITableView!
var TableData:Array< String > = Array < String >()
override func viewDidLoad() {
super.viewDidLoad()
get_data_from_url("http://www.stevenbunting.org/Alliris/service.php")
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return TableData.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
cell.textLabel?.text = TableData[indexPath.row]
return cell
}
func get_data_from_url(_ link:String)
{
let url:URL = URL(string: link)!
let session = URLSession.shared
let request = NSMutableURLRequest(url: url)
request.httpMethod = "GET"
request.cachePolicy = NSURLRequest.CachePolicy.reloadIgnoringCacheData
let task = session.dataTask(with: request as URLRequest, completionHandler: {
(
data, response, error) in
guard let _:Data = data, let _:URLResponse = response , error == nil else {
return
}
self.extract_json(data!)
})
task.resume()
}
func extract_json(_ data: Data)
{
let json: Any?
do
{
json = try JSONSerialization.jsonObject(with: data, options: [])
}
catch
{
return
}
guard let data_list = json as? NSArray else
{
return
}
if let countries_list = json as? NSArray
{
for i in 0 ..< data_list.count
{
if let country_obj = countries_list[i] as? NSDictionary
{
if let country_name = country_obj["user"] as? String
{
if let country_code = country_obj["friendlist"] as? String
{
TableData.append(country_name + " [" + country_code + "]")
}
}
}
}
}
DispatchQueue.main.async(execute: {self.do_table_refresh()
})
}
func do_table_refresh()
{
self.tableView.reloadData()
}
}
Probably you didn't set the tableView's dataSource. To do this, implement the UITableViewDataSource-protocol in the ViewController-class and set the tableView's dataSource-property to self in the viewDidLoad(), for example:
class ViewController: UIViewController, UITableViewDataSource {
// ...
override func viewDidLoad() {
super.viewDidLoad()
tableView.dataSource = self
// ...
}
//...
}
Oh, and don't forget about the Apple Transport Security-settings, otherwise you won't see anything as iOS doesn't allow HTTP anymore, you have use HTTPS. The right way to handle this is to get an SSL-Certificate for your domain.
The quick'n'dirty and absolutely not recommended way is to disable ATS or to set an exception for certain, trustworthy domains.
I have managed to retrieve data from JSON using swiftJSON but I am facing problems when i try to populate tableview. I am new to iOS development, so please bear with me on this. I would appreciate if you could help or provide some ideas ?
Here's the code:
override func viewDidLoad(){
super.viewDidLoad()
getContactListJSON()
}
func getContactListJSON(){
let urlString = "http://jsonplaceholder.typicode.com/users"
let urlEncodedString = urlString.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)
let url = NSURL( string: urlEncodedString!)
var task = NSURLSession.sharedSession().dataTaskWithURL(url!) {(data, response, innerError) in
let json = JSON(data: data)
let contactsArray = json.arrayValue
dispatch_async(dispatch_get_main_queue(), {
for contacts in contactsArray
{
let id = contacts["id"].stringValue
let name = contacts["name"].stringValue
println( "id: \(id) name: \(name)" )
}
})
}
task.resume()
}
Here is your complete code for that:
import UIKit
class TableViewController: UITableViewController {
var tableName = [String]()
var tableID = [String]()
override func viewDidLoad() {
super.viewDidLoad()
getContactListJSON()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func getContactListJSON(){
let urlString = "http://jsonplaceholder.typicode.com/users"
let urlEncodedString = urlString.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)
let url = NSURL( string: urlEncodedString!)
var task = NSURLSession.sharedSession().dataTaskWithURL(url!) {(data, response, innerError) in
let json = JSON(data: data)
let contactsArray = json.arrayValue
dispatch_async(dispatch_get_main_queue(), {
for contacts in contactsArray
{
let id = contacts["id"].stringValue
let name = contacts["name"].stringValue
println( "id: \(id) name: \(name)" )
self.tableName.append(name)
self.tableID.append(id)
}
dispatch_async(dispatch_get_main_queue(),{
self.tableView.reloadData()
})
})
}
task.resume()
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return tableName.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! TableViewCell
// Configure the cell...
cell.id.text = tableID[indexPath.row]
cell.name.text = tableName[indexPath.row]
return cell
}
}
And HERE is working sample project for you with custom cell.
First declare a local variable NSArray called contactsArray.
override func viewDidLoad(){
super.viewDidLoad()
getContactListJSON()
}
//Code for downloading data
func getContactListJSON(){
let urlString = "http://jsonplaceholder.typicode.com/users"
let urlEncodedString = urlString.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)
let url = NSURL( string: urlEncodedString!)
var task = NSURLSession.sharedSession().dataTaskWithURL(url!) {(data, response, innerError) in
let json = JSON(data: data)
self.contactsArray = json.arrayValue
dispatch_async(dispatch_get_main_queue(), {
[self.tableView reloadData]
})
}
task.resume()
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.contactsArray.count;
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell:UITableViewCell = self.tableView.dequeueReusableCellWithIdentifier("cell") as UITableViewCell
var contacts:NSDictionary = self.contactsArray[indexPath.row];
cell.textLabel?.text = contacts["name"].stringValue
//.......
//.......
return cell
}
Here is a piece of code.
var dataArray = [String]()
override func viewDidLoad(){
super.viewDidLoad()
getContactListJSON()
}
func getContactListJSON(){
let urlString = "http://jsonplaceholder.typicode.com/users"
let urlEncodedString = urlString.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)
let url = NSURL( string: urlEncodedString!)
var task = NSURLSession.sharedSession().dataTaskWithURL(url!) {(data, response, innerError) in
let json = JSON(data: data)
let contactsArray = json.arrayValue
dispatch_async(dispatch_get_main_queue(), {
for contacts in contactsArray
{
let id = contacts["id"].stringValue
let name = contacts["name"].stringValue
println( "id: \(id) name: \(name)" )
self.dataArray.append(name)
}
self.tableView.reloadData()
})
}
task.resume()
}
Here i am taking name. If you want to display id as well, then create a model class for it.