简体   繁体   English

反序列化对象 C#

[英]Deserialize an Object C#

I have the following json:我有以下 json:

{
    "coord":{"lon":-88.92,"lat":44.46},
    "weather":[{"id":600,"main":"Snow","description":"light snow","icon":"13d"}],
    "main":{"temp":271.72,"pressure":1009,"humidity":73,"temp_min":269.15,"temp_max":273.15},
    "name":"XXXXX",
}

and I'm trying to deserialize in C# using this classes:我正在尝试使用这些类在 C# 中反序列化:

public class weatherClass
{

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

    [JsonProperty("main")]
    public Info Main { get; set;}

    [JsonProperty("weather")]
    public List<InfoWeather> Weather { get; set; }
}

public class Info{
    public string temp { get; set;}
    public string pressure { get; set;}
}

public class InfoWeather {
    public string description { get; set;}
    public string main { get; set;}
}

I can acces to temp and pressure from Info Class.我可以从 Info Class 访问温度和压力。 But I'm having problems with InfoWeather.但是我在使用 InfoWeather 时遇到了问题。 It doesn't return anything:它不返回任何内容:

weatherResult.Text = string.Format("The city is: {0} and the description is: {1}", weatherlass.Name, weatherlass.Weather);

If I use weatherlass.Weather.description如果我使用weatherlass.Weather.description

在此处输入图片说明

/*Change your class definitions to use proper case names then use the camel case converter provide by newtonsoft*/

public class WeatherClass
{
    public string Name { get; set; }
    public Info Main { get; set; }
    public List<InfoWeather> Weather { get; set; }
}

public class Info
{
    public string Temp { get; set; }
    public string Pressure { get; set; }
}

public class InfoWeather
{
    public string Description { get; set; }
    public string Main { get; set; }
}

var jsonSerializerSettings = new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() };
var weatherClass = Newtonsoft.Json.JsonConvert.DeserializeObject<WeatherClass>(json, jsonSerializerSettings);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM