128

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 its state is inconsistent. To investigate its state the Visual Studio debugger view is useless. But the object has a data contract. I'd like to serialize it and then use my favorite text editor to navigate across the object. Is it possible to do the from the debugger?

2
  • Note, that if you have some custom container class, or some other class what you want to see many times during debug, but the IntelliSense and QuickView cannot figure it out, you can write an extension for VS which helps to show your custom class in debug.
    – Csaba Toth
    Sep 13, 2013 at 20:34
  • Many good techniques can also be found [here] (stackoverflow.com/questions/360277/…)
    – Josh
    Jul 1, 2015 at 19:43

12 Answers 12

245

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)

9
  • 33
    Wish I could upvote this again, especially compared to the other answers. (Sorry, but I don't need to see another line of XML in my career.)
    – yzorg
    Nov 21, 2014 at 15:43
  • 1
    After a very long test debug session an exception happened in my program before it could write out thousands of test results to a file, I was on a breakpoint where the exception occurred and could still inspect the results collection. This tip saved me a lot of time!
    – HAL9000
    Dec 1, 2015 at 3:10
  • 1
    You might need to actually use Json.Net somewhere else too so that it is loaded when you try to use it in the Immediate window (as opposed to just adding the reference).
    – Evan
    Feb 17, 2017 at 22:25
  • 1
    I had to add the Newtonsoft.Json package using Nuget, and also add a line of code in the method that I had the breakpoint in to create a dummy Newtonsoft.Json.JsonArrayAttribute() class to get it to work. A most excellent solution! Jan 17, 2018 at 19:47
  • 4
    This is a great answer. I use it with just a tiny change to save me a trip to the beautifier. Newtonsoft.Json.JsonConvert.SerializeObject(someVariable, Newtonsoft.Json.Formatting.Indented)
    – Jamie
    Feb 1, 2020 at 3:27
99

Some time ago I wrote this one-liner serializing an object to a file on the disk. Copy/paste it to your Immediate window, and replace obj (it's referenced twice) with your object. It'll save a text.xml file to c:\temp, change it to your liking.

(new System.Xml.Serialization.XmlSerializer(obj.GetType())).Serialize(new System.IO.StreamWriter(@"c:\temp\text.xml"), obj)

Don't expect any magic though, if the object cannot be serialized, it'll throw an exception.

5
  • 4
    This worked for me in the immediate window. upvoted, Feb 16, 2016 at 13:40
  • 1
    when I use this on the VS 2015 immediate window, I get this 'error': "Evaluation of native methods in this context is not supported." Ideas?
    – Vetras
    Oct 14, 2016 at 10:25
  • When I run it, I get the following message: identifier "System" is undefined
    – Rasoul
    Aug 29, 2017 at 8:00
  • Had an old VB.NET project, had to put it like this otherwise I was getting an error about expression syntax, if anyone needs: new System.Xml.Serialization.XmlSerializer(obj.GetType()).Serialize(New System.IO.StreamWriter("C:\temp\temp.txt"), obj) Jan 16, 2018 at 16:26
  • This is spectacular. I had to use a different directory due to write permissions, but it worked like a charm. Import into Excel and it's even pretty.
    – R-D
    Mar 19, 2019 at 21:18
40

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#

6
  • 5
    That link seems to be broken, but here is the github project and you can find it if you search for "Object Exporter" in the "Extensions and Updates..." dialog in Visual Studio. Great extension btw! May 18, 2015 at 6:35
  • 2
    Thank you @Omar The idea is perfect. But it takes too long time and freeze in some cases Feb 22, 2017 at 11:47
  • 1
    Agreed with @WahidBitar - Great concept - perfect for setting up unit test data, but the extension seems quite buggy, and takes Visual Studio with it when it crashes!
    – Dib
    Mar 22, 2018 at 13:47
  • 7
    Version for Visual Studio 2019 Sep 24, 2020 at 13:57
  • 1
    @OmarElabd, would you mind publishing this for VS 2019 and @022?
    – FoxDeploy
    Nov 1, 2021 at 13:50
23

Since .NET Core 3.0 you can use System.Text.Json:

System.Text.Json.JsonSerializer.Serialize(obj)
15

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))
5

Object Dumper is a free and open-source extension for Visual Studio and Visual Studio Code.

"Dump as" commands are available via context menu in the Code and Immediate windows.

It's exporting objects to:

  • C# object initialization code,
  • JSON,
  • Visual Basic object initialization code,
  • XML,
  • YAML.

I believe that combined with the Diff tool it can be helpful.

I'm the author of this tool.

7
  • it seems like a great tool, but are you planning a python version ?
    – geriwald
    Feb 15 at 15:52
  • @geriwald Do you mean IronPython for Visual Studio? Is it still alive? Feb 16 at 9:02
  • No, it was a genuine question.
    – geriwald
    Feb 17 at 6:40
  • Unfortunately, python is not in my technology stack. Feb 17 at 10:16
  • 1
    Thanks, man! this extension really helps!
    – fsbflavio
    Feb 28 at 14:02
3

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));
}
3

It might be possible to use the immediate window to serialize it and then copy the content to your favorite editor.

Another option is to override the ToString() method and call it while in debug mode.

You can also write the contents out to a file shortly before the crash, or wrap the code into a try/catch and write the file then. I'm assuming you can identify when it's crashing.

1
  • Thanks, I tried same from Watch window, but it told me "The function evaluation requires all threads to run." Immediate window solve it
    – xvorsx
    Sep 13, 2013 at 20:04
2

In case you have a circular reference, run this in the immediate Window:

Newtonsoft.Json.JsonConvert.SerializeObject(app, Newtonsoft.Json.Formatting.Indented,
new Newtonsoft.Json.JsonSerializerSettings
{
    ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize
});
1
  • 1
    It's a nice sample, containing full namespaces is a big advantage. Changing "ReferenceLoopHandling.Serialize" as "ReferenceLoopHandling.Ignore" could be a faster and "errorless" alternative for many cases. Dec 7, 2022 at 8:38
2

I've been using ObjectDumper.Net.

It works well, especially if you have live unit testing. I can easily view a variable's value in the console when a test runs, saving me from debugging manually.

This may help if you're using XUnit.

1

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.

1
  • Looked promising, but didn't work for me at all.
    – Leon V
    Jun 10, 2021 at 0:59
0

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.