41
loading...
This website collects cookies to deliver better user experience
{
"id": 1,
"name": "Peyman",
"create_date": "2021-07-14T00:00:00"
}
Edit > Paste Special > Paste JSON As Classes
functionality in Visual Studio to paste the above JSON, it will generate a class like this:public class Person
{
public int id { get; set; }
public string name { get; set; }
public DateTime create_date { get; set; }
}
JsonPropertyAttribute
to specify the property name for serialization and de-serialization purposes.public class Person
{
[JsonProperty("id")]
public int Id { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("create_date")]
public DateTime CreateDate { get; set; }
}
DataContractAttribute
, DataMemberAttribute
instead of Json.NET's own attributes:[DataContract]
public class Person
{
[DataMember(Name = "id")]
public int Id { get; set; }
[DataMember(Name = "name")]
public string Name { get; set; }
[DataMember(Name = "create_date")]
public DateTime CreateDate { get; set; }
}
System.Text.Json
has its own attributes:public class Person
{
[JsonPropertyName("id")]
public int Id { get; set; }
[JsonPropertyName("name")]
public string Name { get; set; }
[JsonPropertyName("create_date")]
public DateTime CreateDate { get; set; }
}
System.Text.Json
doesn't support DataContract
and DataMember
attributes. This brings us to the main point of this post:The System.Text.Json
or any major JSON libraries should support DataContract
and DataMember
attributes.
Is there a particular reason why the new
JsonPropertyName
attribute won't work for your scenario?
For example, if we build a Blazor app, and ofc we'd like to make JSON models shared between our server and client to keep them consistent, but on the client side (i.e. Blazor project), we can't use System.Text.Json
due to the runtime restrictions so we can't use JsonPropertyName
.
What's more, many existing projects now use DataContract
/DataMember
attributes because it's common and most of JSON libs respect it.
I knew that now it's life after WCF, and we'd better not use these attributes introduced by WCF since it's nearly EoS. But we need attributes that could describe JSON models across so many JSON libs and runtime.
We don't currently have plans to support the attributes from System.Runtime.Serialization