I recently discovered a feature in the most amazing IDE in the cosmos .. otherwise known as Visual Studio.
Myself and some fellow developers were having a discussion about AngularJS and JSON data. As you may expect we started talking about ways to get the JSON data into our C# classes.
During that discussion one guy mentioned this feature of Studio that I had no idea existed.
Edit > Paste Special > Paste JSON As Classes
So what exactly does that do for you? Let’s say you had the following JSON in an AngularJS viewmodel and you want a matching C# class for later to represent all that data.
Ok, there is not a lot of data but stick with me here anyway, k?
If you’re doing a lot of WebAPI-with-C# work, as I am, you might enjoy the feature where you can use the [FromBody] attribute to essentially map your incoming json data to a strongly-typed class.
The reason I bring that feature up is because this works incredibly well with this Paste Special feature. You create your JSON and then create C# classes from them, which will virtually guarantee success when passing the JSON to C# using the [FromBody] attribute.
Ok we’ve gotten this far but how do we actually get this JSON into a class? Cause hey we may be using [FromBody] but man our fingers are tired of typing .. and we’re lazy developers after all .. oh c’mon admit it you’re lazy too!
So enter the Paste Special feature.
Copy your JSON to ye old clipboard by highlighting it as shown above, choose Paste Special like so …
And viola! Instant C# class that will map all nice and pretty-like. Notice that it even gets the property types correct. Sweetness!
I really dig this feature and hope you do too. As you can see, our class still needs a little TLC by renaming the Rootobject to something more constructive. Do notice how the child-object was broken out into it’s own class. Very handy.
So that’s how to use Paste JSON as Classes
Have other features of Visual Studio that you really dig/can’t do without? Let me know in the comments! Also would love to hear how you’re passing data like this around in your apps.