【问题标题】:How to add json from url in databound app in windows 8 application如何在 Windows 8 应用程序的数据绑定应用程序中从 url 添加 json
【发布时间】:2015-10-12 18:52:37
【问题描述】:

我想在我正在使用的 Visual Basic 2013 中的数据绑定应用程序中添加来自 url 的 json .....但我找不到任何方法可以做到这一点。

。我想从 json url
添加数据 .第二个我还想展示图片
.左边是图片,右边是文字。

JSON 示例是:

{"worldpopulation":[{"titlejson":"Bullish trend observed in KSE with 300 points increase","titledesc":25695,"flag":""}]} 

我如何将该 json 获取到 windows phone

我想在MainViewmodel.cs这个页面加载数据

    public void LoadData()
        {
            // Sample data; replace with real data
            this.Items.Add(new ItemViewModel() { ID = "0", LineOne = "runtime one", LineTwo = "Maecenas praesent accumsan bibendum", LineThree = "Facilisi faucibus habitant inceptos interdum lobortis nascetur pharetra placerat pulvinar sagittis senectus sociosqu" });

            this.Items.Add(new ItemViewModel() { ID = "0", LineOne = "runtime one", LineTwo = "Maecenas praesent accumsan bibendum", LineThree = "Facilisi faucibus habitant inceptos interdum lobortis nascetur pharetra placerat pulvinar sagittis senectus sociosqu" });

            this.IsDataLoaded = true;
        }

【问题讨论】:

  • 您是否尝试使用服务?
  • 是来自 url 的 json 服务

标签: c# json windows-phone-8 visual-studio-2013


【解决方案1】:

您需要有适合您的 json 结果的模型。

模型对应你的json结果

您可以使用json2csharp生成模型

public class Worldpopulation
{
  public string titlejson { get; set; }
  public int titledesc { get; set; }
  public string flag { get; set; }
}

 public class RootObject 
{
  public List<Worldpopulation> worldpopulation { get; set; }
}

您的视图模型加载数据方法应使用 HttpClient 调用 Web 服务以获取您的 json 结果。它将反序列化到您的模型,然后您可以转移到您的视图模型

LoadData()Method 数据消费服务

 using (HttpClient client = new HttpClient())
            {

                client.BaseAddress = new Uri("http://api.openweathermap.org");

                var url = "data/2.5/forecast/daily?q={0}&mode=json&units=metric&cnt=7";

                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                HttpResponseMessage response = await client.GetAsync(url);

                if (response.IsSuccessStatusCode)
                {
                    var data = response.Content.ReadAsStringAsync();
                    var yourResult= JsonConvert.DeserializeObject<RootObject>(data.Result.ToString());
                }
           //Code to map to your view-model object and bind them to view

            }

【讨论】:

  • 无法理解有两个文件,一个是 main.xaml,另一个是 mainviewmodel.cs,我可以在其中编写此代码
  • 数据与使用 System.Runtime.Serialization 的视图模型中的数据类似;命名空间 PhoneApp1.Models { [DataContract] public class City { [DataMember(Name = "name")] public string Name { get;放; } [DataMember(Name = "countrycode")] 公共字符串 CountryCode { get;放; } [DataMember(Name = "population")] public int Population { get;放; } } }
猜你喜欢
  • 1970-01-01
  • 2013-03-26
  • 2023-03-16
  • 1970-01-01
  • 2012-06-13
  • 1970-01-01
  • 2012-06-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多