using System.Text.Json to serialize and deserialize object
Serialize
1 | string json = JsonSerializer.Serialize(poco); |
Deserialize
1 | Poco poco = JsonSerializer.Deserialize<Poco>(json); |
Specified property name
add attribute [JsonPropertyName(name)] on Poco property.
1 | [] |
will serialize as {"summary":1.0.0}
ignore null
ignore propertie serialize when its value is null.
JsonSerializer.Serialize has second param:options to control behavior
set options.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull
1 | var options = new JsonSerializerOptions(){ DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNul}; |
serialize with constructor
add attribute [JsonConstructor] on class constructor
enum to string
serialize enum value to its name(default is numerical) or deserialize.
add JsonStringEnumConverter to options.Converters
1 | var options = new JsonSerializerOptions(){Converters={new JsonStringEnumConverter()}} |
enum to lower camel case string
convert GenderEnum.Male to "male"
set JsonStringEnumConverter use JsonNamingPolicy.CamelCase
1 | var options = new JsonSerializerOptions(){Converters={new JsonStringEnumConverter(JsonNamingPolicy.CamelCase)}} |
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 AlMirai!