C#json对象反序列化

时间:2018-04-23 07:29:39

标签: c# json weather-api

我有一个JSON内容为

[{
    "LocalObservationDateTime": "2018-04-23T08:10:00+05:00",
    "EpochTime": 1524453000,
    "WeatherText": "Sunny",
    "WeatherIcon": 1,
    "IsDayTime": true,
    "Temperature": {
        "Metric": {
            "Value": 29.6,
            "Unit": "C",
            "UnitType": 17
        },
        "Imperial": {
            "Value": 85.0,
            "Unit": "F",
            "UnitType": 18
        }
    },
    "MobileLink": "http://m.accuweather.com/en/pk/jamaluddinwali/259991/current-weather/259991?lang=en-us",
    "Link": "http://www.accuweather.com/en/pk/jamaluddinwali/259991/current-weather/259991?lang=en-us"
}]

我的课程处理此内容如下:

class AccuWeather
{

    public class RootObject
    {
        public Class1[] Property1 { get; set; }
    }

    public class Class1
    {
        public DateTime LocalObservationDateTime { get; set; }
        public int EpochTime { get; set; }
        public string WeatherText { get; set; }
        public int WeatherIcon { get; set; }
        public bool IsDayTime { get; set; }
        public Temperature Temperature { get; set; }
        public string MobileLink { get; set; }
        public string Link { get; set; }
    }

我刚尝试通过C#中的以下代码片段反序列化此内容:

       private AccuWeather.RootObject Parse_A(string targetURI)
       {
        Uri uri = new Uri(targetURI);

        var webRequest = WebRequest.Create(uri);
        WebResponse response = webRequest.GetResponse();

        AccuWeather.RootObject wUData = null;

        try
        {
            using (var streamReader = new StreamReader(response.GetResponseStream()))
            {
                var responseData = streamReader.ReadToEnd();

                // if you want all the "raw data" as a string
                // just use: responseData.ToString()

                wUData = JsonConvert.DeserializeObject<AccuWeather.RootObject<Class1>>(responseData);
            }
        }
        catch (Exception e)
        {
            MessageBox.Show(e.Message);
        }

        return wUData;
    }//completed

我不确定这是反序列化JSON内容的正确有效方法。在这种情况下,任何人都能提供一些关于最佳实践的详细信息吗 提前感谢任何帮助!

2 个答案:

答案 0 :(得分:1)

您也可以使用.NET动态,例如

var json = @"[{""LocalObservationDateTime"": ""2018-04-23T08:10:00+05:00"",
                ""EpochTime"": 1524453000,
                ""WeatherText"": ""Sunny"",
                ""WeatherIcon"": 1,
                ""IsDayTime"": true,
                ""Temperature"": {
                    ""Metric"": {
                        ""Value"": 29.6,
                        ""Unit"": ""C"",
                        ""UnitType"": 17
                    },
                    ""Imperial"": {
                        ""Value"": 85.0,
                        ""Unit"": ""F"",
                        ""UnitType"": 18
                    }
                },
                ""MobileLink"": ""http://m.accuweather.com/en/pk/jamaluddinwali/259991/current-weather/259991?lang=en-us"",
                ""Link"": ""http://www.accuweather.com/en/pk/jamaluddinwali/259991/current-weather/259991?lang=en-us""
            }]";

dynamic accuWeatherResp = JArray.Parse(json);
if (accuWeatherResp.Count == 0)
{
    Console.WriteLine("Response is Empty");
    return;
}
dynamic weather = accuWeatherResp[0];
if (weather != null)
{
    Console.WriteLine("Observation time: {0:s} Weather: {1}, Temperature: {2: 0.0} °C", weather.LocalObservationDateTime, weather.WeatherText, weather.Temperature.Metric.Value);
}

答案 1 :(得分:0)

有一个名为quicktype.io的页面,您可以在其中粘贴JSON并接收C#类和相应的转换器代码:

using System.Globalization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;

public partial class Welcome
{
    [JsonProperty("LocalObservationDateTime")]
    public DateTimeOffset LocalObservationDateTime { get; set; }

    [JsonProperty("EpochTime")]
    public long EpochTime { get; set; }

    [JsonProperty("WeatherText")]
    public string WeatherText { get; set; }

    [JsonProperty("WeatherIcon")]
    public long WeatherIcon { get; set; }

    [JsonProperty("IsDayTime")]
    public bool IsDayTime { get; set; }

    [JsonProperty("Temperature")]
    public Temperature Temperature { get; set; }

    [JsonProperty("MobileLink")]
    public string MobileLink { get; set; }

    [JsonProperty("Link")]
    public string Link { get; set; }
}

public partial class Temperature
{
    [JsonProperty("Metric")]
    public Imperial Metric { get; set; }

    [JsonProperty("Imperial")]
    public Imperial Imperial { get; set; }
}

public partial class Imperial
{
    [JsonProperty("Value")]
    public double Value { get; set; }

    [JsonProperty("Unit")]
    public string Unit { get; set; }

    [JsonProperty("UnitType")]
    public long UnitType { get; set; }
}

public partial class Welcome
{
    public static Welcome[] FromJson(string json) => JsonConvert.DeserializeObject<Welcome[]>(json, QuickType.Converter.Settings);
}

public static class Serialize
{
    public static string ToJson(this Welcome[] self) => JsonConvert.SerializeObject(self, QuickType.Converter.Settings);
}

internal static class Converter
{
    public static readonly JsonSerializerSettings Settings = new JsonSerializerSettings
    {
        MetadataPropertyHandling = MetadataPropertyHandling.Ignore,
        DateParseHandling = DateParseHandling.None,
        Converters = {
                new IsoDateTimeConverter { DateTimeStyles = DateTimeStyles.AssumeUniversal }
            },
    };
}