【问题标题】:How can I deserialization JSON in Windows Phone?如何在 Windows Phone 中反序列化 JSON?
【发布时间】:2013-01-07 05:01:14
【问题描述】:

第一个 JSON 看起来像 this

第二个 JSON 看起来像 this

如何反序列化它们?我一直关注这个example,但它不起作用。 这是我的代码。

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            var w = new WebClient();
            Observable
              .FromEvent<DownloadStringCompletedEventArgs>(w, "DownloadStringCompleted")
              .Subscribe(r =>
              {
                  var deserialized =
                    JsonConvert.DeserializeObject<List<Place>>(r.EventArgs.Result);
                  PlaceList.ItemsSource = deserialized;
              });
            w.DownloadStringAsync(
              new Uri("http://mobiilivantaa.lightscreenmedia.com/api/place"));

            //For 2nd JSON
            //w.DownloadStringAsync(
                 //new Uri("http://mobiilivantaa.lightscreenmedia.com/api/place/243"));

        }

这些是第一个 JSON 的类。

        public class Place
        {
            public string id { get; set; }
            public string title { get; set; }
            public string latitude { get; set; }
            public string longitude { get; set; }
            public string www { get; set; }
        }

        public class RootObjectJSON1
        {
            public List<Place> Places { get; set; }
        }

这些是 JSON2 的类

public class Address
{
    public string street { get; set; }
    public string postal_code { get; set; }
    public string post_office { get; set; }
}

public class Image
{
    public string id { get; set; }
    public string filename { get; set; }
    public string path { get; set; }
}

public class RootObjectJSON2
{
    public string id { get; set; }
    public string title { get; set; }
    public string description { get; set; }
    public string latitude { get; set; }
    public string longitude { get; set; }
    public string www { get; set; }
    public string phone { get; set; }
    public string email { get; set; }
    public string contact_person { get; set; }
    public Address address { get; set; }
    public List<Image> images { get; set; }
}

【问题讨论】:

    标签: json deserialization windows-phone


    【解决方案1】:

    看起来您应该反序列化对象 RootObjectJSON1 或 RootObjectJSON2,例如:

    var deserialized = JsonConvert.DeserializeObject<RootObjectJSON1>(r.EventArgs.Result);
    

    另外,集合 Places 似乎应该以小写 p 开头,或者你需要告诉 Json.NET 这个属性应该用不同的名称反序列化,例如:

    [JsonProperty(PropertyName="places")]
    public List<Place> Places { get; set; }
    

    通常我倾向于使用数组进行反序列化(根据我的经验效果更好),所以我建议将其重写为:

    public class RootObjectJSON1
    {
        public Place[] places { get; set; }
    }
    

    http://json2csharp.com/ 上有一个名为 json2csharp 的非常好的工具 - 只需将 JSON 样本放在那里,它就会在 C# 中输出类(不检测 DateTime,因此您可能需要更改它)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多