开发者

How would I safely get these JSON values from an API response if I don't know the keys?

Example response:

"release_dates": {
    "theater": "1939-12-15",
    "dvd": "2000-03-07"
},

I don't know if a movie will have a dvd, vhs开发者_如何学Go, betamax or blu ray release. Because of this I just can't hardcode what types are available and put try catches all over the place checking if it's there or not. I'd rather do this correctly by getting the types available first, then getting the values for the available types.

Here's what I have so far, using the JSON.Net library:

var releaseDates = (JArray) x["release_dates"];
foreach (var releaseDate in releaseDates)
{
    ReleaseDate date = new ReleaseDate()
                           {
                               Type = releaseDate
                           }
}

Is there some way to get the key name, and the value name?

My ReleaseDate class has the following:

public class ReleaseDate
{
    public string Type { get; set; }
    public DateTime Date { get; set; }
}


Here's how you do it:

var dates = (JObject)x["release_dates"];
foreach (var date in dates)
{
    ReleaseDate releaseDate = new ReleaseDate();

    releaseDate.Type = (string)date.Key;

    var tmpDate = ((string) date.Value).Substring(0, ((string) date.Value).Count());
    releaseDate.Date = DateTime.Parse(tmpDate);

    movie.ReleaseDates.Add(releaseDate);
}


Assuming that the values are always of type DateTime an alternate approach would be to deserialize directly into a Dictionary, e.g.

using System;
using System.Collections.Generic;
using NUnit.Framework;
using Newtonsoft.Json;

namespace JsonNET
{
    [TestFixture]
    public class JsonNetExamples
    {
        class ReleaseDateCollection
        {
            [JsonProperty(PropertyName = "release_dates")]
            public Dictionary<string, DateTime> ReleaseDates { get; set; }
        }

        [Test]
        public void DerializeReleaseDateCollection()
        {
            const string json = @"{""release_dates"":{""theater"": ""1939-12-15"",""dvd"": ""2000-03-07"",""bluray"": ""1977-05-25""}}";
            var collection = JsonConvert.DeserializeObject<ReleaseDateCollection>(json);
            Assert.AreEqual(new DateTime(1939, 12, 15), collection.ReleaseDates["theater"]);
            Assert.AreEqual(new DateTime(2000, 3, 7), collection.ReleaseDates["dvd"]);
            Assert.AreEqual(new DateTime(1977, 5, 25), collection.ReleaseDates["bluray"]);
        }
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜