如果我不知道密钥,我如何安全地从API响应中获取这些JSON值?

时间:2011-04-16 23:25:29

标签: c# json json.net

回复示例:

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

我不知道电影是否会有dvd,vhs,betamax或蓝光版本。因此,我无法对可用的类型进行硬编码,并尝试抓住所有地方,检查它是否存在。我宁愿通过先获取类型,然后获取可用类型的值来正确执行此操作。

这是我到目前为止所使用的JSON.Net库:

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

有没有办法获取密钥名称和值名称?

我的ReleaseDate课程包含以下内容:

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

2 个答案:

答案 0 :(得分:1)

这是你如何做到的:

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

答案 1 :(得分:0)

假设值始终是DateTime类型,另一种方法是直接反序列化为Dictionary,例如

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"]);
        }
    }
}