簡體   English   中英

嘗試反序列化 JSON 返回 null 值

[英]Trying to deserialize JSON returns null values

使用方法 JsonConvert.DeserializeObject 返回所有屬性的默認值。

var current = JsonConvert.DeserializeObject<Current>(myJson);
{
    "location": {
        "name": "London"
    },
    "current": {
        "temp_c": 5.0,
        "cloud": 50
    }
}
public class Current
{
    public double Temp_c { get; set; }
    public double Cloud { get; set; }
}

預期的當前 object 應具有以下值: Cloud為 50, Temp_c為 5.0,但返回所有屬性的默認值。

您需要定義一個 class model 像 json object 然后反序列化它

public class YourModel {

   //create location class that has Name property
   public Location Location { get; set; }

   //create current class that has Temp_c and Cloud property
   public Current Current { get; set; }

}

接着

var data = JsonConvert.DeserializeObject<YourModel>(myJson);

並從數據 object 中獲取當前值

var current = data.Current;

您的“當前”class 遠不像您發布的 JSON。

您需要將 JSON 字符串轉換為 C# class。您可以使用QuickType進行轉換(與 Newtonsoft 兼容)。

注意:我正在使用 System.Text.Json.Serialization 但 class model 應該相等,只需更改:

[JsonPropertyName("temp_c")] // .Net serializer (I prefer this)

[JsonProperty("temp_c")] // Newtonsoft.Json serializer

(為每個名字替換“temp_c”)

這是您需要的 class model(一個完整的控制台應用程序):

using System;
using System.Text.Json;
using System.Text.Json.Serialization;

#nullable disable

namespace test
{
    public class Weather
    {
        [JsonPropertyName("location")]
        public Location Location { get; set; }

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

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

    public class Current
    {
        [JsonPropertyName("temp_c")]
        public double TempC { get; set; }

        [JsonPropertyName("cloud")]
        public int Cloud { get; set; }
    }


    class Program
    {
        static void Main(string[] args)
        {
            string json = "{\"location\": { \"name\": \"London\" }, \"current\": { \"temp_c\": 5.0, \"cloud\": 50 }}";
            Weather myWeather = JsonSerializer.Deserialize<Weather>(json);

            Console.WriteLine("Location: {0} - Temp: {1:F}", myWeather.Location.Name, myWeather.Current.TempC);
        }
    }
}

現在反序列化器可以正常工作了。

暫無
暫無

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

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