简体   繁体   English

如何覆盖属性的 JSON 序列化,以将值序列化为字符串而不是 object?

[英]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 .现在你可以看到我忽略了CreatedByUserLastModifiedByUser 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:现在,要使用转换器,您有几个选择:

  1. 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:如果您只想将AbstractBaseUser属性序列化为字符串,请使用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
  2. 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
  3. Or, you could add it to your global JsonSerializerSettings.Converters .或者,您可以将其添加到您的全局JsonSerializerSettings.Converters中。 To do this in .NET Framework, see this answer to Json.net global settings by Andrei .要在 .NET 框架中执行此操作,请参阅AndreiJson.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 中自定义响应序列化的答案

  4. .NET Core 3.x and later use a difference serializer, , 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, , 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 ? . .

Demo fiddle here .演示小提琴在这里

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用Json.Net将对象序列化为JSON字符串属性而不是对象 - How to serialize an object to a JSON string property instead of an object using Json.Net 如何使用Dictionary序列化对象 <string,object> 属性? - How can I serialize an object with a Dictionary<string,object> property? 如何在 json 序列化时使用 DefaultContractResolver 覆盖具有字符串值的复杂类型属性 - How to override complex type property with string value using DefaultContractResolver while json serialization 如何序列化json以显示属性值而不是属性名称? - How to serialize json in order to display property value instead of property name? DataContract序列化 - 我可以序列化Type属性吗? - DataContract Serialization - Can I serialize a Type Property? 如何在没有类对象的情况下使用 json 序列化 int 值? - How can I serialize an int value with json without class object? 通过字符串转换反序列化枚举时,如何获取空值而不是序列化错误? - How can I get a null value instead of a serialization error when deserializing an enum by string conversion? 如何将序列化和反序列化为IDictionary <string,object> 在Json.Net - How can I serialize and deserialize dynamic as IDictionary<string,object> in Json.Net JSON.NET:将 json 字符串属性序列化为 json 对象 - JSON.NET: Serialize json string property into json object 如何在没有某些属性名称的情况下序列化对象 - How can I serialize object without some property names
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM