0

第一个 JSON 看起来像这样

第二个 JSON 看起来像这样

我怎样才能反序列化它们?我一直在关注这个例子,但它不起作用。这是我的代码。

        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; }
}
4

1 回答 1

2

看起来您应该反序列化对象 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,因此您可能需要更改它)。

于 2013-01-07T07:06:14.210 回答