Reference preserving JSON.NET

CSharp · Console

/Program.cs

using System;
using System.Collections;
using System.Linq;
using System.Text;
using Newtonsoft.Json;

public class Program
{
    public static void Main(string[] args)
    {
        string text = "{\"Code\":-2146232800,\"ExceptionType\":\"IOException\",\"Message\":\"Msg\",\"Stacktrace\":\"Some\"}";
        var obj = JsonConvert.DeserializeObject<FileUploadError>(text);
        Console.WriteLine(obj.Code);
    }
}

public class FileUploadError
{
    public FileUploadError(Exception exception)
    {
        Code = exception.HResult;
        ExceptionType = exception.GetType().Name;
        Message = GetMessage(exception);
        Stacktrace = exception.StackTrace;
        if (exception.Data.Count > 0)
        {
            Data = string.Join(Environment.NewLine, exception.Data.Cast<DictionaryEntry>().Select(x => x.Key + "=" + x.Value));
        }
    }

    private string GetMessage(Exception exception)
    {
        if (exception.InnerException == null)
        {
            return exception.Message;
        }
        const string delimiter = "->";
        var sb = new StringBuilder(1024);
        for (var ex = exception; ex != null; ex = ex.InnerException)
        {
            sb.Append(ex.Message).Append(delimiter);
        }
        sb.Length -= delimiter.Length;
        return sb.ToString();
    }
    
    [JsonProperty("Code", NullValueHandling = NullValueHandling.Ignore)]
    public int Code { get; set; }
    [JsonProperty("ExceptionType", NullValueHandling = NullValueHandling.Ignore)]
    public string ExceptionType { get; set; }
    [JsonProperty("Message", NullValueHandling = NullValueHandling.Ignore)]
    public string Message { get; set; }
    [JsonProperty("Stacktrace", NullValueHandling = NullValueHandling.Ignore)]
    public string Stacktrace { get; set; }
    [JsonProperty("Data", NullValueHandling = NullValueHandling.Ignore)]
    public string Data { get; set; }
}
;