Serialization of class fields in System.Text.Json
System.Text.Json in .NET Core 3 introduces support for object serialization and deserialization. However, a problem often arises when trying to serialize class fields using this library.
Consider the following example:
<code>public class Car { public int Year { get; set; } // 正确序列化 public string Model; // 未序列化 }</code>
When trying to serialize a Car instance, the generated JSON string does not contain fields such as Model. This is because System.Text.Json in .NET Core 3 does not support serialized fields.
Solution
In .NET 5 and above, System.Text.Json has the ability to serialize fields. This can be achieved by enabling field support or manually marking the fields for serialization.
Enable field serialization
When serializing, you can enable field serialization by setting the JsonSerializerOptions.IncludeFields property to true:
<code>Car car = new Car { Model = "Fit", Year = 2008 }; // 启用字段序列化 var options = new JsonSerializerOptions { IncludeFields = true }; // 传递 "options" 进行序列化 var json = JsonSerializer.Serialize(car, options);</code>
Mark fields to be serialized
Alternatively, you can use the [JsonInclude] attribute to mark individual fields to be serialized:
<code>[JsonInclude] public string Model;</code>
Examples of two methods
<code>public class Car { public int Year { get; set; } // 正确序列化 [JsonInclude] public string Model; } // 或 Car car = new Car { Model = "Fit", Year = 2008 }; var options = new JsonSerializerOptions { IncludeFields = true }; var json = JsonSerializer.Serialize(car, options);</code>
By implementing these techniques, you can ensure that serialized and deserialized objects have exactly the same values, including values in class fields.
The above is the detailed content of How to Serialize Class Fields Using System.Text.Json in .NET?. For more information, please follow other related articles on the PHP Chinese website!