Visual Studio how to serialize object from debugger

后端 未结 10 1136
轻奢々
轻奢々 2020-12-22 16:39

I\'m trying to investigate a bug in a crash dump (so I can not change the code). I have a really complicated object (thousands of lines in the serialized representation) and

相关标签:
10条回答
  • 2020-12-22 17:20

    Here is a Visual Studio extension which will let you do exactly that:

    https://visualstudiogallery.msdn.microsoft.com/c6a21c68-f815-4895-999f-cd0885d8774f

    You can output to JSON, XML or C#

    0 讨论(0)
  • 2020-12-22 17:21

    With any luck you have Json.Net in you appdomain already. In which case pop this into your Immediate window:

    Newtonsoft.Json.JsonConvert.SerializeObject(someVariable)

    0 讨论(0)
  • 2020-12-22 17:23

    A variation on Alexey's answer. Slightly more complicated but doesn't involve writing to a text file:

    1) In the Immediate Window enter:

    System.IO.StringWriter stringWriter = new System.IO.StringWriter();  
    

    2) In the Watch Window enter two watches:

    a.  stringWriter
    
    b.  new System.Xml.Serialization.XmlSerializer(obj.GetType()).Serialize(stringWriter, obj) 
    

    After you enter the second watch (the Serialize one) the stringWriter watch value will be set to obj serialized to XML. Copy and paste it. Note that the XML will be enclosed in curly braces, {...}, so you'll need to remove them if you want to use the XML for anything.

    0 讨论(0)
  • 2020-12-22 17:24

    Use this in Visual Studio's "Immediate" window, replacing c:\directory\file.json with the full path to the file to which you'd like to write the JSON and myObject with your variable to serialise:

    System.IO.File.WriteAllText(@"c:\directory\file.json", Newtonsoft.Json.JsonConvert.SerializeObject(myObject))
    
    0 讨论(0)
  • 2020-12-22 17:30

    I have an extension method I use:

    public static void ToSerializedObjectForDebugging(this object o, FileInfo saveTo)
    {
        Type t = o.GetType();
        XmlSerializer s = new XmlSerializer(t);
        using (FileStream fs = saveTo.Create())
        {
            s.Serialize(fs, o);
        }
    }
    

    I overload it with a string for saveTo and call it from the immediate window:

    public static void ToSerializedObjectForDebugging(this object o, string saveTo)
    {
        ToSerializedObjectForDebugging(o, new FileInfo(saveTo));
    }
    
    0 讨论(0)
  • 2020-12-22 17:31

    A variation on the answer from Omar Elabd --

    It's not free, but there's a free trial for OzCode
    (https://marketplace.visualstudio.com/items?itemName=CodeValueLtd.OzCode).

    There's built-in exporting to JSON within the context/hover menu there, and it works a bit better than the Object Export extension (the trade-off for it not being free).

    http://o.oz-code.com/features#export (demo)

    I know this is a few years after the fact, but I'm leaving an answer here because this worked for me, and someone else may find it useful.

    0 讨论(0)
提交回复
热议问题