Serializing custom exception object

It's a .net core project running on a Mac. I've a custom Exception class that I'm serializing as JSON as output in case of an error.

  public class HttpException : Exception {
    private readonly int statusCode;

    public HttpException() {}

    public HttpException(int statusCode, string message) : base(message) {
        this.statusCode = statusCode;
    }

    public int StatusCode {get {return this.statusCode;}}
}

Code related to json serialization

Exception exception = (Exception)serviceRequest.ResultData;
MemoryStream memoryStream = new MemoryStream();  
DataContractJsonSerializer dataContractJsonSerializer = new DataContractJsonSerializer(typeof(Exception));  


// it fails here
dataContractJsonSerializer.WriteObject(memoryStream, exception);  


byte[] json = memoryStream.ToArray();  
memoryStream.Close();  
Console.WriteLine(Encoding.UTF8.GetString(json, 0, json.Length));

System.Runtime.Serialization.SerializationException: Type 'Service.Model.Exceptions.HttpException' with data contract name 'HttpException:http://schemas.datacontract.org/2004/07/Service.Model.Exceptions' is not expected. Add any types not known statically to the list of known types - for example, by using the KnownTypeAttribute attribute or by adding them to the list of known types passed to DataContractSerializer. at System.Runtime.Serialization.XmlObjectSerializerWriteContext.SerializeAndVerifyType(DataContract dataContract, XmlWriterDelegator xmlWriter, Object obj, Boolean verifyKnownType, RuntimeTypeHandle declaredTypeHandle, Type declaredType)

Edit

Trying to use System.Web.Extensions but have squiggly lines.

enter image description here

1 answer

  • answered 2018-03-13 21:31 Eser

    I wish but I can't fall outside with 3rd party libraries, only native implementations because of some requirements.

    You can include the System.Web.Extensions library and use JavaScriptSerializer

    var ser = new JavaScriptSerializer();
    string json = ser.Serialize(exception);
    

    But as I said in comments, I would prefer Json.Net