将json数据添加到listview

时间:2017-12-15 17:07:29

标签: c# android json listview xamarin.android

我正在尝试使用api返回的json数据向我的listview添加数据,我有一个具有列表结构的类,但是当我尝试使用for循环添加数据时它失败并且不会添加它,它尝试运行循环一次然后退出循环。在预期列表时,它的计数为0.

ListAvivity.cs

dynamic mFarms = JsonConvert.DeserializeObject(content);

List<MyList.Data> mItems = new List<FarmsList.Data>();

foreach(var items in mFarms.data)
{
  mItems.Add(new MyList.Data() {FarmID = items["FarmID"].ToString(), FarmerSurname = items["FarmerSurname"].ToString(), 
                FarmerForename = items["FarmerForename"].ToString(), FarmName = items["FarmName"].ToString()});
}

MyList.cs

public class MyList
{
    public class Data
    {
        public int FarmID { get; set; }
        public string FarmName { get; set; }
        public string FarmerSurname { get; set; }
        public string FarmerForename { get; set; }
    }

    public class RootObject
    {
        public int code { get; set; }
        public string status { get; set; }
        public string message { get; set; }
        public Data data { get; set; }
    }

}

Json Data

{
"code": 201,
"status": "Success",
"message": "Object found",
"data": [
    {
        "FarmID": 1,
        "FarmName": "Test1",
        "FarmerSurname": "Test",
        "FarmerForename": "Test"
    },
    {
        "FarmID": 2,
        "FarmName": "Test2",
        "FarmerSurname": "Test",
        "FarmerForename": "Test"
    }
  ]
 }

1 个答案:

答案 0 :(得分:1)

程序没有进入循环,因为你无法反序列化json对象。我建议您将其反序列化为已知类型,而不是dynamic

创建json类;

public class Datum
{
    public int FarmID { get; set; }
    public string FarmName { get; set; }
    public string FarmerSurname { get; set; }
    public string FarmerForename { get; set; }
}

public class Content
{
    public int code { get; set; }
    public string status { get; set; }
    public string message { get; set; }
    public List<Datum> data { get; set; }
}

然后反序列化它;

var mFarms = JsonConvert.DeserializeObject<Content>(content);
List<MyList.Data> mItems = new List<FarmsList.Data>();

foreach(var items in mFarms.data)
{
  mItems.Add(new MyList.Data() {FarmID = items["FarmID"].ToString(), FarmerSurname = items["FarmerSurname"].ToString(), 
                FarmerForename = items["FarmerForename"].ToString(), FarmName = items["FarmName"].ToString()});
}

另外,要打印mItems,请构建一个循环;

foreach (var mitem in mItems)
{
    Console.WriteLine(mitem.FarmID);
    Console.WriteLine(mitem.FarmerSurname);
    //etc
}