我想序列化這個類的屬性(只有 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
}
uj5u.com熱心網友回復:
嘗試使用 Json opt-in 序列化屬性并使用 JsonProperty 指定應序列化的屬性。
[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"
}
uj5u.com熱心網友回復:
你基本上在這里混合了兩個不同的問題。例外只是指示錯誤并且將被拋出給某個錯誤處理程式的東西。盡管它有訊息并且可能有錯誤代碼或類似的東西,但它實際上并沒有任何資料。特別是它不會有名為IsSuccess.
這里的另一件事是data,你只是傳遞它,但它本身沒有任何意義。Exception因此,您應該首先不繼承,或者通過創建一些具有這四個屬性的資料交換類來分離這兩個問題:
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; }
}
現在很容易序列化那個。只需將您的例外包裝到該交換類中:
json = JsonConvert.SerializeObject(new MyExchangeClass { IsSuccess = ... });
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/422889.html
標籤:
上一篇:通過webhook和PS腳本觸發的MSTeams警報不想決議多行文本
下一篇:陣列中的陣列:jq:error(attest.json:91):object({"locations...)isnotvalidinacsvrow
