Home > Backend Development > C++ > How to Serialize Class Fields Using System.Text.Json in .NET?

How to Serialize Class Fields Using System.Text.Json in .NET?

Mary-Kate Olsen
Release: 2025-01-14 06:21:44
Original
700 people have browsed it

How to Serialize Class Fields Using System.Text.Json in .NET?

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>
Copy after login

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>
Copy after login

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template