System.Text.Json: Serialization and Deserialization Fields
In newer .NET versions, System.Text.Json.JsonSerializer
is the preferred JSON serialization and deserialization method. However, it poses a challenge for classes containing field variables, as these are not supported by default.
The problem
In older versions of .NET, field variables could be included in the serialization/deserialization process. With the introduction of JsonSerializer
, only attributes are supported, leading to the following issues:
<code class="language-csharp">using System.Text.Json; public class Car { public int Year { get; set; } // 正确序列化 public string Model; // 未正确序列化(字段变量) } static void Problem() { Car car = new Car() { Model = "Fit", Year = 2008, }; string json = JsonSerializer.Serialize(car); // {"Year":2008} Car carDeserialized = JsonSerializer.Deserialize<Car>(json); Console.WriteLine(carDeserialized.Model); // null! }</code>
Solution
To solve this problem, two strategies exist:
1. .NET 5 and above
Starting in .NET 5, public fields can be serialized and deserialized via:
JsonSerializerOptions.IncludeFields
to true
[JsonInclude]
attributes to fieldsExample:
<code class="language-csharp">using System.Text.Json; using System.Text.Json.Serialization; static void Main() { var car = new Car { Model = "Fit", Year = 2008 }; // 启用支持 var options = new JsonSerializerOptions { IncludeFields = true }; // 传递“options” var json = JsonSerializer.Serialize(car, options); // 传递“options” var carDeserialized = JsonSerializer.Deserialize<Car>(json, options); Console.WriteLine(carDeserialized.Model); // 输出 "Fit" } public class Car { public int Year { get; set; } [JsonInclude] public string Model; }</code>
2. .NET Core 3.x
In .NET Core 3.x, field serialization is not supported. As a workaround, consider using a custom converter to achieve the desired behavior.
For more information and detailed documentation, please refer to the following resources:
The above is the detailed content of How Can I Serialize and Deserialize Fields Using System.Text.Json?. For more information, please follow other related articles on the PHP Chinese website!