簡體   English   中英

在c#中從嵌套的Json中提取數據

[英]Extracting data out of nested Json in c#

我想為windows phone開發一個天氣應用程序。我創建了一個用於測試目的的簡單UI。包含一個帶有文本框和按鈕的網格以輸入城市名稱。第二個網格有不同的標簽,用於在點擊按鈕后顯示天氣數據。

我正在使用openweathermap.org中的 api。我用Json數據創建了類:

{"coord":{"lon":-120.5,"lat":47.5},"sys":{"message":0.195,"country":"US","sunrise":1384787560,"sunset":1384820527},"weather":[{"id":800,"main":"Clear","description":"sky is clear","icon":"01d"}],"base":"gdps stations","main":{"temp":277.15,"pressure":1010,"humidity":86,"temp_min":277.15,"temp_max":277.15},"wind":{"speed":0.31,"deg":230.5},"rain":{"3h":1},"clouds":{"all":1},"dt":1384797300,"id":5815135,"name":"Washington","cod":200}

這些課程是:

    public class Coord
{
    public double lon { get; set; }
    public double lat { get; set; }
}

public class Sys
{
    public double message { get; set; }
    public string country { get; set; }
    public int sunrise { get; set; }
    public int sunset { get; set; }
}

public class Weather
{
    public int id { get; set; }
    public string main { get; set; }
    public string description { get; set; }
    public string icon { get; set; }
}

public class Main
{
    public double temp { get; set; }
    public double temp_min { get; set; }
    public double temp_max { get; set; }
    public double pressure { get; set; }
    public double sea_level { get; set; }
    public double grnd_level { get; set; }
    public int humidity { get; set; }
}

public class Wind
{
    public double speed { get; set; }
    public double deg { get; set; }
}

public class Clouds
{
    public int all { get; set; }
}

public class RootObject
{
    public Coord coord { get; set; }
    public Sys sys { get; set; }
    public List<Weather> weather { get; set; }
    public string  { get; set; }
    public Main main { get; set; }
    public Wind wind { get; set; }
    public Clouds clouds { get; set; }
    public int dt { get; set; }
    public int id { get; set; }
    public string name { get; set; }
    public int cod { get; set; }
}

我正在使用Json.net從獲取的json中提取數據。我的Json數據沒有列表但只有一個對象。我已經看到了如何在xaml中將列表綁定到ListItem的示例。但是我不知道該怎么做在單個對象上。 XAML:

<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>
        <Grid x:Name="boxOfSearch" Grid.Row="0">
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="8*"/>
                <ColumnDefinition Width="2*" />
            </Grid.ColumnDefinitions>
            <TextBox x:Name="getEnteredString" Margin="2,1"/>
            <Button Grid.Column="1" x:Name="btnGet" Tap="btnGet_Tap">Go</Button>
            <!--<Button x:Name="goButton" Content="Go" Grid.Column="1" Margin="2,1"                         Click="goButton_Click"/>-->
        </Grid>

        <Grid Grid.Row="1" x:Name="extractedData" Height="532">
    <Grid.RowDefinitions>
                <RowDefinition Height="3*"/>
                <RowDefinition Height="1*"/>
    <RowDefinition Height="1*"/>
                </Grid.RowDefinitions>
                        <TextBlock x:Name="getName" Text="{Binding name}"  Margin="2,2,2,5" Foreground="#FF176EB5" FontSize="48" TextAlignment="Center" />

我想要的輸出是:城市名稱,高溫和低溫。名稱和溫度來自不同的類別。如果我能分別得到這些值,它對我來說可能是一個很好的起點。

    private void btnGet_Tap(object sender, GestureEventArgs e)
    {
        WebClient wc = new WebClient();
        wc.DownloadStringAsync(new Uri(""));
        wc.DownloadStringCompleted += new DownloadStringCompletedEventHandler(wc_DownloadStringCompleted);
    }

    void wc_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
    {

        MessageBox.Show(e.Result);                        

        var rootObj=JsonConvert.DeserializeObject<RootObject>(e.Result);  //Getting DeserializedObject in a variable
        getJsonStrTxtBox.Text = rootObj.name;       // var.name  where name (Name of the City) is a string in RootObject class
    }                                                //like var.name add var.main.temp_max

現在我可以從嵌套的json中獲取任何數據。 Json.net和@evanmcdonnal非常感謝你。

城市名稱加溫度

我對你的問題感到有些困惑,但聽起來你真的只是想找到這樣的東西;

    RootObject response = JsonConvert.DeserializeObject<RootObject>(responseBody);

    string message = String.Format("City: {0} - high: {1}, low: {2}", response.name, response.main.temp_max, response.main.temp_mix);

     MessageBox.Show(message);

注意:我會建議一些無效的檢查,我沒有包含在上面的例子中(是響應null?好的,是response.main null?)。 當您在復雜對象上使用json.NET的DeserializeObject方法時,反序列化是“級聯”(缺少更好的術語)意味着您要反序列化的類的所有對象也將被適當地反序列化。 從那里你可以像任何其他對象一樣訪問它們,只有另一層間接。

使用http://james.newtonking.com/json

 class Program
    {
        static void Main(string[] args)
        {
            var json =
                "{\"coord\":{\"lon\":-120.5,\"lat\":47.5},\"sys\":{\"message\":0.195,\"country\":\"US\",\"sunrise\":1384787560,\"sunset\":1384820527},\"weather\":[{\"id\":800,\"main\":\"Clear\",\"description\":\"sky is clear\",\"icon\":\"01d\"}],\"base\":\"gdps stations\",\"main\":{\"temp\":277.15,\"pressure\":1010,\"humidity\":86,\"temp_min\":277.15,\"temp_max\":277.15},\"wind\":{\"speed\":0.31,\"deg\":230.5},\"rain\":{\"3h\":1},\"clouds\":{\"all\":1},\"dt\":1384797300,\"id\":5815135,\"name\":\"Washington\",\"cod\":200}";

            dynamic obj = JsonConvert.DeserializeObject(json);

            Console.WriteLine(obj.coord.lon + "  " + obj.coord.lat);

            Console.ReadLine(); 
        }
    }

首先提取數據並將其映射到類。 然后處理UI事件。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM