[英]How can I override the JSON serialization for a property, to serialize the value as a string instead of an object?
Using.Net 4.8 I have all my entity framework classes inheriting from an AbstractBase:使用.Net 4.8,我的所有实体框架类都继承自 AbstractBase:
public abstract class AbstractBase
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public virtual int Id { get; set; }
public virtual DateTime CreatedTimestamp { get; set; }
public virtual DateTime UpdatedTimestamp { get; set; }
[Required]
public virtual int CreatedBy { get; set; }
[Required]
public virtual int LastModifiedBy { get; set; }
public virtual bool ActiveFlag { get; set; }
[JsonIgnore]
public virtual User CreatedByUser { get; set; }
[JsonIgnore]
public virtual User LastModifiedByUser { get; set; }
public string ToActiveInactive()
{
return this.ActiveFlag ? "Active" : "Inactive";
}
}
Now as you can see I am ignoring the CreatedByUser
and LastModifiedByUser
.现在你可以看到我忽略了
CreatedByUser
和LastModifiedByUser
。 What I would like to do instead is somehow replace the User object with a property called FullName which the User object can provide like我想做的是以某种方式将用户 object 替换为用户 object 可以提供的名为 FullName 的属性,例如
User test = new User();
test.GetFullName();
My User object already has this so my question is there a way to do this so I do not have to write more implementation of the same logic every time I want to serialize an entity class?我的用户 object 已经有了这个,所以我的问题是有没有办法做到这一点,所以每次我想序列化一个实体 class 时,我不必编写更多相同逻辑的实现?
You can create a custom JsonConverter<T>
like the one shown in the Newtonsoft documentation to serialize your User
class as a string:您可以创建一个自定义
JsonConverter<T>
,如Newtonsoft 文档中所示,将您的User
class 序列化为字符串:
public class UserConverter : JsonConverter<User>
{
public override void WriteJson(JsonWriter writer, User value, JsonSerializer serializer)
{
writer.WriteValue(value.GetFullName());
}
public override User ReadJson(JsonReader reader, Type objectType, User existingValue, bool hasExistingValue, JsonSerializer serializer)
{
var fullName = serializer.Deserialize<string>(reader);
// Or construct a User and return it, if you can do so from the fullName.
throw new NotImplementedException();
}
}
Note that your question does not provide enough information for me to write the ReadJson()
method.请注意,您的问题没有为我提供足够的信息来编写
ReadJson()
方法。 If you need to support deserialization, you will need to fully implement this method by constructing a User
from the fullName
string.如果您需要支持反序列化,则需要通过从
fullName
字符串构造一个User
来完全实现此方法。
Now, to use the converter, you have several options:现在,要使用转换器,您有几个选择:
If you only want the User
properties of AbstractBase
to be serialized as strings, apply the converter to the User
properties using JsonConverterAttribute
as follows:如果您只想将
AbstractBase
的User
属性序列化为字符串,请使用JsonConverterAttribute
将转换器应用于User
属性,如下所示:
public abstract class AbstractBase { [JsonConverter(typeof(UserConverter))] public virtual User CreatedByUser { get; set; } [JsonConverter(typeof(UserConverter))] public virtual User LastModifiedByUser { get; set; } // Remaining properties and methods unchanged
If you want all instances of User
of to be serialized as a string, you can apply it directly to User
as follows:如果您希望将
User
的所有实例序列化为字符串,则可以将其直接应用于User
,如下所示:
[JsonConverter(typeof(UserConverter))] public class User { // Properties and methods unchanged
Or, you could add it to your asp.net-web-api2 global JsonSerializerSettings.Converters
.或者,您可以将其添加到您的asp.net-web-api2全局
JsonSerializerSettings.Converters
中。 To do this in .NET Framework, see this answer to Json.net global settings by Andrei .要在 .NET 框架中执行此操作,请参阅Andrei对Json.net 全局设置的回答。 For .NET Core 2.x see this answer to Customizing response serialization in ASP.NET Core MVC by Métoule .
对于 .NET Core 2.x,请参阅 Métoule 在ASP.NET Core MVC 中自定义响应序列化的答案。
.NET Core 3.x and later use a difference serializer, system.text.json , so you will have to use a different approach in that version, or revert back to using Json.NET as shown in Where did IMvcBuilder AddJsonOptions go in.Net Core 3.0? .NET Core 3.x and later use a difference serializer, system.text.json , so you will have to use a different approach in that version, or revert back to using Json.NET as shown in Where did IMvcBuilder AddJsonOptions go in.Net Core 3.0 ? .
.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.