C# - Требуется доступ к JSON значениям данных из моего объекта Dynami c - PullRequest
1 голос
/ 30 мая 2020

У меня есть json данные, как показано ниже -

{
    "request": {
        "type": "",
        "query": "",
        "language": "en",
        "unit": "m"
    },
    "location": {
        "name": "",
        "country": "",
        "region": "",
        "lat": "",
        "lon": "",
        "timezone_id": "Asia/Kolkata",
        "localtime": "2020-05-29 23:30",
        "localtime_epoch": 1590795000,
        "utc_offset": "5.50"
    },
    "current": {
        "observation_time": "06:00 PM",
        "temperature": 40,
        "weather_code": 116,
        "weather_icons": [
            ""
        ],
        "weather_descriptions": [
            "Partly cloudy"
        ],
        "wind_speed": 9,
        "wind_degree": 230,
        "wind_dir": "SW",
        "pressure": 1006,
        "precip": 0,
        "humidity": 26,
        "cloudcover": 25,
        "feelslike": 42,
        "uv_index": 1,
        "visibility": 6,
        "is_day": "no"
    },
    "forecast": {
        "2020-05-28": {
            "date": "2020-05-28",
            "date_epoch": 1590624000,
            "astro": {
                "sunrise": "05:41 AM",
                "sunset": "06:46 PM",
                "moonrise": "10:29 AM",
                "moonset": "11:48 PM",
                "moon_phase": "First Quarter",
                "moon_illumination": 39
            },
            "mintemp": 32,
            "maxtemp": 44,
            "avgtemp": 38,
            "totalsnow": 0,
            "sunhour": 13.1,
            "uv_index": 9
        }
    }
}

Первые три узла («запрос», «местоположение», «текущий») привязаны правильно, но для «прогноза» с первого узла это дата и время. Я написал следующим образом:

var dataObjects = JsonConvert.DeserializeObject<Location_Weather.Weather>(customerJsonString);                   
var dataObjects23 = JsonConvert.DeserializeObject<Dictionary<string, dynamic>> (customerJsonString);
dynamic forecast_details = dataObjects23["forecast"];

Это моя модель ->

public class New_Location_Weather
    {

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

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

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

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

    public partial class Current
    {
        [JsonProperty("observation_time")]
        public string ObservationTime { get; set; }

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

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

        [JsonProperty("weather_icons")]
        public Uri[] WeatherIcons { get; set; }

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

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

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

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

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

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

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

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

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

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

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

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

    public partial class Forecast
    {
        [JsonProperty("2020-05-28")]
        public The20200528 The20200528 { get; set; }
    }

    public partial class The20200528
    {
        [JsonProperty("date")]
        public DateTimeOffset Date { get; set; }

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

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

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

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

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

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

        [JsonProperty("sunhour")]
        public double Sunhour { get; set; }

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

    public partial class Astro
    {
        [JsonProperty("sunrise")]
        public string Sunrise { get; set; }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    public partial class Request
    {
        [JsonProperty("type")]
        public string Type { get; set; }

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

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

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

Теперь проблема в том, что я не могу получить значения. Мне нужно руководство о том, как получить эти значения из объекта Dynami c, который является pred_details, в мой C# код . Ниже приведен снимок экрана со значениями, которые мне нужны для доступа к ним в моем c# коде

При отладке объекта Dynami c я нашел значения в моем представлении результатов. Но я не уверен, как получить доступ к этим значениям в моем коде c#.

Пожалуйста, дайте мне знать, как получить эти значения из моего объекта C# Dynami c (прогноз_details).

Ответы [ 2 ]

0 голосов
/ 30 мая 2020

Это то, что я понял. Надеюсь, это поможет другим.

JObject obj = JObject.Parse(customerJsonString);
var forecast_details = obj.SelectToken("forecast").Children().OfType<JProperty>()
                                    .ToDictionary(p => p.Name, p => new
                                    {
                                        MaxTemp = (int)p.First()["maxtemp"],
                                        MinTemp = (int)p.First()["mintemp"]
                                    });
if(forecast_details.Count>0)
{
  int max_temp = forecast_details.Values.Select(x => x.MaxTemp).FirstOrDefault();
  int min_temp = forecast_details.Values.Select(x => x.MinTemp).FirstOrDefault();
}
0 голосов
/ 30 мая 2020

Посмотрите на этот вопрос, есть два ответа, которые могут вам помочь.

Как добавить свойства во время выполнения к JSON (C#)

Вы можете проанализировать свой прогноз json в JObject и получить из него все значения с помощью foreach.

...