【问题标题】:Cannot print the json message in listview using xamarin cross platform无法使用 xamarin 跨平台在 listview 中打印 json 消息
【发布时间】:2014-10-31 23:24:43
【问题描述】:

使用 xamarin 跨平台开发,我想从 url 打印一条 json 消息并在 listview 中打印。我编写代码没有错误,但有一些错误。我不会工作。仅对于验证输出,我在输出屏幕中打印按钮。我将显示但未打印列表视图。请更正我的代码。

    static ListView listview;
    static Button button;
    public MainPage()
    {
        listview = new ListView() { RowHeight = 40 };
        button = new Button() { Text = "search Again" };
        var stack = new StackLayout()
        {
            VerticalOptions = LayoutOptions.FillAndExpand,
            Children = { button, listview },
        };
        this.Content = stack;
        GetData();
    }
     async static void GetData()
    {
        WeatherReport res = new WeatherReport();
        try
        {
            string contents;
            string Url = String.Format("http://23.253.66.248:8080/icc/api/venue/search/?                lat=39.540544&lon=-104.866115&appkey=123Chesse&restName=MyMacChennai&organization=MyMacChennai");
            HttpClient hc = new HttpClient();
            contents = await hc.GetStringAsync(Url);
            res = JsonConvert.DeserializeObject<WeatherReport>(contents);
            listview.ItemsSource = res.list;
        }
        catch (System.Exception sysExc)
        {
            // Do something to log this error.
            throw;
        }
    }
 public class WeatherReport
 {
    public WeatherReport()
    {
        list = new List<WeatherReport>();
    }
    [JsonProperty(PropertyName = "cod")]
    public string cod { get; set; }
    [JsonProperty(PropertyName = "message")]
    public string message { get; set; }
    [JsonProperty(PropertyName = "cnt")]
    public int cnt { get; set; }
    [JsonProperty(PropertyName = "list")]
    public List<WeatherReport> list { get; set; }

【问题讨论】:

  • 您确认您的数据被正确填充了吗?

标签: json listview xamarin.ios xamarin cross-platform


【解决方案1】:

首先,您不应该使用async void,除了事件处理程序,这是不好的做法。其次,GetData() 是一个异步方法,但是您在构造函数中同步调用它。我建议重新设计一下,使其始终保持异步。您可能会遇到问题,因为您正在等待代码完成后再继续。代码中的其他所有内容显示正常。

这里有一些额外的资源可能有助于异步/等待。 http://msdn.microsoft.com/en-us/magazine/jj991977.aspx, async/await - when to return a Task vs void?

【讨论】:

    猜你喜欢
    • 2018-04-03
    • 2014-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-05
    • 1970-01-01
    • 1970-01-01
    • 2018-10-03
    相关资源
    最近更新 更多