有没有一种方法可以序列化某些不是基础 class 的 属性 的属性?使用牛顿软件

Is there a way to serialize certain properties that are not property of the base class? using Newtonsoft

我想序列化此 class 属性(仅 IsSuccess、StatusCode、Description、Messages) 但是 Newtonsoft 序列化了所有属性 base 和 BaseException 属性

public class BaseException :  Exception
{
    public bool IsSuccess { get; set; }
    public int StatusCode { get; set; }
    public string Description { get; set; }
    public string Messages { get; set; }
    public BaseException(int statusCode, string message, string description)
    {
        StatusCode = statusCode;
        IsSuccess = false;
        Description = description;
        Messages = message;
    }
    public BaseException()
    {

    }

} 

我在异常中间件中使用的序列化方法

    private string ConvertJsonData(Exception e, int statusCode)
    {
        string json="";
        var type = e.GetType();
        if (e.GetType() == typeof(BaseException))
        {
            json = JsonConvert.SerializeObject(new BaseException
            {
                IsSuccess = (bool)type.GetProperty("IsSuccess").GetValue(e),
                StatusCode = statusCode,
                Messages = (string)type.GetProperty("Messages").GetValue(e),
                Description = (string)type.GetProperty("Description").GetValue(e),
                
            });
        }
        return json;
    }

我抛出 BaseException:

throw new BaseException(404, "Not Found", "Kullanıcı Bulunamadı"); 

json 来自控制器的响应:

{
  "StatusCode": 404,
  "IsSuccess": false,
  "Messages": "Not Found",
  "Description": "Kullanıcı Bulunamadı",
  "StackTrace": null,
  "Message": "Exception of type 'SharedNote.Application.Exceptions.BaseException' was thrown.",
  "Data": {},
  "InnerException": null,
  "HelpLink": null,
  "Source": null,
  "HResult": -2146233088
}

您实际上是在混淆两种不同的关注点。异常只是指示错误的东西,它是要抛给某些 error-handler 的东西。尽管有消息,但它实际上没有任何数据,可能是 error-code 或类似的东西。特别是它不会有叫做 IsSuccess.

的东西

这里的另一件事是数据,你只是传递它,但它本身没有任何意义。因此,您应该首先通过不继承 Exception 或通过创建具有这四个属性的 data-exchange-class 来将这两个问题分开:

class MyExchangeClass // does NOT inherit Exception
{
    public bool IsSuccess { get; set; }
    public int StatusCode { get; set; }
    public string Description { get; set; }
    public string Messages { get; set; }
}

现在很容易连载那个。只需将您的异常包装到 exchange-class:

json = JsonConvert.SerializeObject(new MyExchangeClass { IsSuccess = ... });

尝试使用 Json opt-in 序列化属性并指定应序列化的 Json属性 属性。

[JsonObject(MemberSerialization.OptIn)]
public class BaseException :  Exception
{
    [JsonProperty]
    public bool IsSuccess { get; set; }
    [JsonProperty]
    public int StatusCode { get; set; }
    [JsonProperty]
    public string Description { get; set; }
    [JsonProperty]
    public string Messages { get; set; }

       .... another properties

}

测试

var ex= new BaseException(404,"message","description");
JsonConvert.SerializeObject(ex, Newtonsoft.Json.Formatting.Indented);

结果

{
  "IsSuccess": false,
  "StatusCode": 404,
  "Description": "description",
  "Messages": "message"
}