2014-03-12 139 views
0

我正在爲C#中的iOS開發Xamarin項目。從Json列表填充TableView

我有一個包含4個項目的Json文件。我希望他們填充TableView,但只顯示Json文件中的最後一項。

這是我得到的JSON文件列表:

StreamReader strm = new StreamReader (filePath); 
response = strm.ReadToEnd(); 

List<Field> items = JsonConvert.DeserializeObject<List<Field>>(response); 

爲了顯示這些項目的TableView中我創建了一個這樣的數組:

int count = items.Count; 
string[] tableItems = new string[count]; 

我試圖填補該陣列是這樣的:

foreach(Field item in items) 
{ 
    tableItems = new string[] { item.Value }; 
} 
table.Source = new TableSource(tableItems); 
Add(table); 

這是TableSource:

public TableSource (string[] items) 
{ 
    TableItems = items; 
} 

這是甚至可能的,我怎樣才能實現它,所以我的Json項目是在一個TableView?

編輯

這是Json文件。我分析它只是在一個視圖控制器和它的工作,但不是在TableViewController ..

[{ 
'id': 0, 
'type': 'textField', 
'value': 'Vul hier je voornaam in.', 
'extra': '' 
},{ 
'id': 1, 
'type': 'textField', 
'value': 'Vul hier je achternaam in.', 
'extra': '' 
},{ 
'id': 2, 
'type': 'textField', 
'value': 'Vul je gebruikersnaam in.', 
'extra': '' 
},{ 
'id': 3, 
'type': 'textField', 
'value': 'Vul je wachtwoord in.', 
'extra': 'password' 
}] 
+0

你可以發佈你試圖反序列化的JSON嗎? – Dave

+0

我檢查了foreach循環中tableItems的長度,它始終爲1.問題出現在某處.. –

回答

0

你可以採取的C#的功能,如LINQ的優勢,使其成爲一個更簡單的方法:

 table.Source = new TableSource(
      JsonConvert.DeserializeObject<List<Field>> (response). 
      Select (a => a.Value). 
      ToArray() 
     ); 

您當前的代碼存在的問題是,如果Id的索引不是0並且順序不匹配,您將遇到異常。如果你想分類的項目,那麼你可以添加排序很容易:

 table.Source = new TableSource(
      JsonConvert.DeserializeObject<List<Field>> (response). 
      OrderBy(s => s.Id). 
      Select (a => a.Value). 
      ToArray() 
+0

如果我需要從列表中選擇多個值並將它與Where函數結合,該怎麼辦? –

+0

這是一個枚舉,所以你可以標記任何你想要的東西。你想讓源代碼包含Field的集合嗎? Hre是一個可能有用的鏈接:http://msdn.microsoft.com/en-us/library/system.linq.enumerable_methods(v=vs.110).aspx – SKall

+0

已經工作了,謝謝:) –

0

我已經從本文的例子固定它:http://www.dotnetperls.com/string-array

我foreach循環是現在爲大家誰具有以下同樣的問題:

foreach(Field item in items) 
{ 
    tableItems[item.Id] = item.Value; 
}