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.
// it fails here
with what error? – Matt Burlandnew DataContractJsonSerializer(typeof(HttpException));
, I usedException
before. this brings another question, how can I make it generic because system can throw different kinds of exceptions, do I've to narrow down totypeof
each? – App2015string json = JsonConvert.SerializeObject(exception);
it will work – Eser