C#, Code, Tips, Visual Studio

Visual Studio – Paste Special – JSON as Classes

This has been there since 2013 I believe, but I’m just now discovering it….wish I would have found it sooner as it’s an awesome feature.

Take a JSON (or XML as there is a Paste XML as Classes as well) like the following and copy it into the clipboard:

{
"People" :[{
    "First Name" : "Jason",
    "Last Name" : "Lautzenheiser", 
    "Address" : {
        "Street" : "1122 Main",
        "City" : "BigTown",
        "State" : "OH",
        "Zip" : 66554
    },
    "Phones" : [{
        "PhoneType" : "Home",
        "Number" : "330-555-7777"
      },
      {
        "PhoneType" : "Work",
        "Number" : "330-222-1111"
      }
    ]
  }]
}

Then under the Edit->Paste Special menu, there is an option for Paste JSON as Classes which will spit out the following code:

public class Rootobject
{
 public Person[] People { get; set; }
}

public class Person
{
 public string FirstName { get; set; }
 public string LastName { get; set; }
 public Address Address { get; set; }
 public Phone[] Phones { get; set; }
}

public class Address
{
 public string Street { get; set; }
 public string City { get; set; }
 public string State { get; set; }
 public int Zip { get; set; }
}

What a beautiful thing that is. I recently had to import and manipulate some JSON data for a report which was much more complex than this. Within minutes I had my object model setup and the JSON files being read in.

Small feature, but what a time saver.

.NET, C#, Tips

IEnumerable to Comma Delimited String

A few years ago I blogged about how to take a delimited string and convert it to a IEnumerable.  Today we ran across the opposite of this in that we wanted to take a list and convert it to a delimited string.   This can come in handy for a number of situations so it’s worth taking a look.

Given:

List<int> values = new List<int> {10, 20, 25};

In older versions of .NET (prior to 4.0 I believe) the easiest way was to do something like the following:

string newString = string.Join(",", values.ToArray());

However, starting in 4.0, the Join has some additional overloads that make this just crazy simple:

string newString = string.Join(",", values);

If you have a list of strings, there is still some benefit to converting this to an array. There is another overload of Join that allows you to be more selective in what you are converting.

Given a list of strings like the following:

List<string> strings = new List<string> {"a", "b", "c", "d", "e", "f"};

We can look at the last overload of; String.Join(delimiter, string[], startIndex, count)

This gives us a delimited string, starting at the element in the array at startIndex and going for the number of count.

string delimited = string.Join(",", strings.ToArray(), 2, 2);

will return “c,d”

I love how the framework provides these methods, often with multiple overloads to give us a lot of power with very little code. Enjoy!