C# json 对象反序列化

C# json object Deserializtion

我有一个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处理此内容如下:

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 内容的正确有效方法。在这种情况下,任何人都可以提供有关最佳做法的一些详细信息吗? 提前感谢任何帮助!

有一个名为 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 }
            },
    };
}

您也可以为此使用 .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);
}