对象C#的JSON(将复杂的API响应映射到C#对象)

时间:2017-09-08 13:40:11

标签: c# api model-view-controller json.net

我能够处理简单的JSON序列化和反序列化,但这个API响应看起来并不复杂,我正在寻求建议,以解决解决此问题的理想方法。

我试图为MVC应用程序调用API。 目标是将API数据映射到模型。 API端点是 https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol=MSFT&interval=1min&apikey=MyAPIKey

这里的麻烦是:

  1. JSON数据键中包含空格。
  2. 当我尝试在Visual Studio中进行特殊粘贴时,它给了我很长时间 每个日期条目的类列表分开,因为这个API call返回一组单独的日期信息。
  3. 为了解决第1点中解释的问题,我在课堂上使用了[JsonProperty("1. Information")]。在我的代码..

            public async Task TSI()
            {
                HttpClient client = new HttpClient();
                //Uri uri = new Uri("http://date.jsontest.com/");
                Uri uri = new Uri("https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol=MSFT&interval=5min&apikey=demo");
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    
                HttpResponseMessage response = await client.GetAsync(uri);
                if (response.IsSuccessStatusCode)
                {
                    dynamic result = await response.Content.ReadAsAsync<object>();
    
                    IEnumerable<dynamic> dObj = JsonConvert.DeserializeObject<dynamic>(result.ToString());
    
                    IEnumerable<dynamic> t1 = dObj.FirstOrDefault();
                    IEnumerable<dynamic> t2 = dObj.LastOrDefault();
                    dynamic MetaData = t1.FirstOrDefault();
    
                    Rootobject ro = new Rootobject();
                    ro.MetaData = MetaData;
    
                }
    

    PS:我做API调用和处理它们相对较新。

    我能够打电话给

      

    date.jsontest.com

    并将API数据映射到模型(我使用特殊粘贴创建)

    //API response
        {
            "time": "12:53:22 PM",
            "milliseconds_since_epoch": 1504875202754,
            "date": "09-08-2017"
        }
    
    //C# code to map to API data
        public class sampleObject
        {
            public string time { get; set; }
            public long milliseconds_since_epoch { get; set; }
            public string date { get; set; }
        }
    

    我的RootObject看起来像这样:

    public class Rootobject
        {
            [JsonProperty("Meta Data")]
            public MetaData MetaData { get; set; }
    
            [JsonProperty("Time Series (1min)")]
            public TimeSeries1Min TimeSeries1min { get; set; }
        }
    
        public class MetaData
        {
            [JsonProperty("1. Information")]
            public string _1Information { get; set; }
    
            [JsonProperty("2. Symbol")]
            public string _2Symbol { get; set; }
    
            [JsonProperty("3. Last Refreshed")]
            public string _3LastRefreshed { get; set; }
    
            [JsonProperty("4. Interval")]
            public string _4Interval { get; set; }
    
            [JsonProperty("5. Output Size")]
            public string _5OutputSize { get; set; }
    
            [JsonProperty("6. Time Zone")]
            public string _6TimeZone { get; set; }
        }
    
    // I have so many of these sub-classes for dates, which again is an issue
        public class TimeSeries1Min
        {
                public _20170907160000 _20170907160000 { get; set; }
                public _20170907155900 _20170907155900 { get; set; }
    ....
    ....}
    
    
    
    public class _20170907160000
        {
            public string _1open { get; set; }
            public string _2high { get; set; }
            public string _3low { get; set; }
            public string _4close { get; set; }
            public string _5volume { get; set; }
        }
    
        public class _20170907155900
        {
            public string _1open { get; set; }
            public string _2high { get; set; }
            public string _3low { get; set; }
            public string _4close { get; set; }
            public string _5volume { get; set; }
        }
    

2 个答案:

答案 0 :(得分:5)

很难从这个json创建一个模型,但你可以将这些数据转换为字典

var jObj = JObject.Parse(json);
var metadata = jObj["Meta Data"].ToObject<Dictionary<string, string>>();
var timeseries = jObj["Time Series (1min)"].ToObject<Dictionary<string, Dictionary<string, string>>>();

答案 1 :(得分:1)

以下代码应该做你想做的事情

       if (response.IsSuccessStatusCode)
        {
            var result = await response.Content.ReadAsStringAsync();

            var obj = JsonConvert.DeserializeObject<Rootobject>(result);
            //No idea what you want to do with this line as there is no MetaData property on the root object
            obj.MetaData = MetaData;

        }