Deserialize Json using dynamic object or model

本秂侑毒 提交于 2019-12-11 08:25:47

问题


I have been trying to convert the below json into a C# model:

{
"Meta Data": {
    "1. Information": "Intraday (1min) prices and volumes",
    "2. Symbol": "MSFT",
    "3. Last Refreshed": "2017-07-25 16:00:00",
    "4. Interval": "1min",
    "5. Output Size": "Compact",
    "6. Time Zone": "US/Eastern"
},
"Time Series (1min)": {
    "2017-07-25 16:00:00": {
        "1. open": "74.2500",
        "2. high": "74.2800",
        "3. low": "74.1900",
        "4. close": "74.1900",
        "5. volume": "2698886"
    },
    "2017-07-25 15:59:00": {
        "1. open": "74.1400",
        "2. high": "74.2600",
        "3. low": "74.1400",
        "4. close": "74.2550",
        "5. volume": "375097"
    },
    "2017-07-25 15:58:00": {
        "1. open": "74.1400",
        "2. high": "74.1500",
        "3. low": "74.1400",
        "4. close": "74.1450",
        "5. volume": "133209"
    }
}
}

I have tried the following:

Controller:

public async Task<IActionResult> Index()
    {

        var client = new HttpClient();
        var task = await client.GetAsync("https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol=MSFT&interval=apiKey");
        var jsonString = await task.Content.ReadAsStringAsync();

//DAY LIST SHOWS NULL
        var dayList = JsonConvert.DeserializeObject<Root>(jsonString).Data;

        dynamic fyn = JsonConvert.DeserializeObject(jsonString); 

        var returntype = fyn.GetType();

        //below i am going to try and format TimeSeriesIntraDayJsonClass which is a manually created model rather than a dynamically created model
        RootTwo obj = new RootTwo();
        obj.Property1 = JsonConvert.DeserializeObject<RootTwo>(jsonString).Property1;

//trying to get properties individually
        JToken token = JObject.Parse(jsonString);
        string high = (string)token.SelectToken("2. high");            

        return View(dayList);

TimeSeriesIntraDay.cs

namespace ApiTest.Models
{
    public class RootTwo
    {
        public Class1[] Property1 { get; set; }
    }

    public class Class1
    {
        [JsonProperty(PropertyName = "Meta Data")]
        public string MetaName { get; set; }
        public Dictionary<string, HeadData> Meta { get; set; }
        [JsonProperty(PropertyName = "Time Series (1min)")]
        public string Title { get; set; }
        //name of each dictionary is the date which is a dynamic value then that name holds the dictionary which has the actual data
        public List<Dictionary<string, Dictionary<ChildrenData, string>>> DateName { get; set; }
    }

    public class HeadData
    {
        [JsonProperty(PropertyName = "1. Information")]
        public string Information { get; set; }
        [JsonProperty(PropertyName = "2. Symbol")]
        public string Symbol { get; set; }
        [JsonProperty(PropertyName = "3. Last Refreshed")]
        public string LastRefrshed { get; set; }
        [JsonProperty(PropertyName = "4. Interval")]
        public string Interval { get; set; }
        [JsonProperty(PropertyName = "5. Output Size")]
        public string OutputSize { get; set; }
        [JsonProperty(PropertyName = "6. Time Zone")]
        public string TimeZone { get; set; }
    }

    public class ChildrenData
    {
        [JsonProperty(PropertyName = "1. open")]
        public string Open { get; set; }
        [JsonProperty(PropertyName = "2. high")]
        public string High { get; set; }
        [JsonProperty(PropertyName = "3. low")]
        public string Low { get; set; }
        [JsonProperty(PropertyName = "4. close")]
        public string Close { get; set; }
        [JsonProperty(PropertyName = "5. volume")]
        public string Volume { get; set; }
    }

}

TimeSeriesIntraDayClass2.cs

namespace ApiTest.Models
{
public class Root
{
    public List<Dictionary<string, TimeSeriesIntraDayJsonClass>> Data { get; set; }
}

public class TimeSeriesIntraDayJsonClass
{
    [JsonProperty(PropertyName = "1. open")]
    public double open { get; set; }
    [JsonProperty(PropertyName = "2. high")]
    public double high { get; set; }
    [JsonProperty(PropertyName = "3. low")]
    public double low { get; set; }
    [JsonProperty(PropertyName = "4. close")]
    public double close { get; set; }
    [JsonProperty(PropertyName = "5. volume")]
    public double volume { get; set; }
}
}

In the controller I have tried to add the json to a model I have created.

I have tried to also create a model class through Edit -> Paste Special -> Paste Json as Classes but it did not work.

Lastly, I created a dynamic object which is returning 2 children tokens; "Meta Data" and "Time Series (1min)". "Time Series (1min)" is in a dictionary, I have tried adding this data to a model I created and also using JToken and getting the data by property but I have had 0 luck. I know there is alot of info on converting JSON data on stackoverflow but I have not been able to figure this out. Can someone please help?


回答1:


UPDATED


Thanks to Aurril. I have tried to deserialize the JSON as a Dictionary and it works. So here is example with classes and with dynamic parse:

Here are classes that you need:

public class Root
{
    [JsonProperty(PropertyName = "Meta Data")]
    public MetaData metaData { get; set; }
    [JsonProperty(PropertyName = "Time Series (15min)")] // You will need to change 15min to the interval you will use
    public Dictionary<string, TimeSeriesIntraDayJsonClass> Data { get; set; }
}

public class MetaData
{
    [JsonProperty(PropertyName = "1. Information")]
    public string Information { get; set; }
    [JsonProperty(PropertyName = "2. Symbol")]
    public string Symbol { get; set; }
    [JsonProperty(PropertyName = "3. Last Refreshed")]
    public DateTime LastRefreshed { get; set; }
    [JsonProperty(PropertyName = "4. Interval")]
    public string Interval { get; set; }
    [JsonProperty(PropertyName = "5. Output Size")]
    public string OutputSize { get; set; }
    [JsonProperty(PropertyName = "6. Time Zone")]
    public string TimeZone { get; set; }
}

public class TimeSeriesIntraDayJsonClass
{
    [JsonProperty(PropertyName = "1. open")]
    public double open { get; set; }
    [JsonProperty(PropertyName = "2. high")]
    public double high { get; set; }
    [JsonProperty(PropertyName = "3. low")]
    public double low { get; set; }
    [JsonProperty(PropertyName = "4. close")]
    public double close { get; set; }
    [JsonProperty(PropertyName = "5. volume")]
    public double volume { get; set; }
}

And here is the code for Deserealization:

var client = new HttpClient();
var task = await client.GetAsync("https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol=MSFT&interval=15min&outputsize=full&apikey=5RO0LRV8R1L6H6ES");
var jsonString =await task.Content.ReadAsStringAsync().Result;


dynamic fyn = JsonConvert.DeserializeObject(jsonString);
Console.WriteLine(fyn["Time Series (15min)"]["2017-07-25 16:00:00"]["1. open"]);

Root res = JsonConvert.DeserializeObject<Root>(jsonString);


来源:https://stackoverflow.com/questions/45325531/deserialize-json-using-dynamic-object-or-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!