使用动态对象或模型反序列化Json [英] Deserialize Json using dynamic object or model

查看:113
本文介绍了使用动态对象或模型反序列化Json的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试将以下json转换为C#模型:

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"
    }
}
}

我尝试了以下操作:

控制器:

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

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

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

在控制器中,我尝试将json添加到我创建的模型中.

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

我还尝试通过Edit-> Paste Special-> Paste Json as Classes创建一个模型类,但是它没有用.

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

最后,我创建了一个动态对象,该对象将返回2个子代币. 元数据"和时间序列(1分钟)". 时间序列(1分钟)"在字典中,我试图将这些数据添加到我创建的模型中,并且还使用JToken并按属性获取数据,但我的运气是0. 我知道有很多关于在stackoverflow上转换JSON数据的信息,但是我还无法弄清楚这一点. 有人可以帮忙吗?

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?

推荐答案

已更新

感谢Aurril.我试图将JSON反序列化为Dictionary,并且它可以正常工作. 因此,这里是带有类和动态解析的示例:

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:

这是您需要的课程:

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

以下是Deserealization的代码:

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

这篇关于使用动态对象或模型反序列化Json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆