Better property names using the DataMember attribute
In my previous post, I demonstrated creating a class to serialize the data returned from the Lipsum.com JSON feed. I wasn't happy with the final result as it used JavaScript formatting for the property names (camel cased).
I prefer Pascal casing on my object properties in C#, so I wanted to quickly show how to change the name of the property on the class.
Here is the new LoremIpsum class definition:
public class LoremIpsum
{
public Feed Feed { get; set; }
}
[DataContract]
public class Feed
{
[DataMember(Name ="lipsum")]
public string Lipsum { get; set; }
[DataMember(Name = "generated")]
public string Generated { get; set; }
[DataMember(Name = "donatelink")]
public string DonateLink { get; set; }
[DataMember(Name = "creditlink")]
public string CreditLink { get; set; }
[DataMember(Name = "creditname")]
public string CreditName { get; set; }
}
You'll first need to add a reference to System.Runtime.Serialization
to your project. Then, include the System.Runtime.Serialization
namespace in your using declarations.
The main()
method now looks like this:
static void Main(string[] args)
{
for (int i = 0; i < 10; i++)
{
// toggle between words and paragraphs
bool isEven = (i % 2).Equals(0); // used this because markdown had trouble with double equal signs
bool isThird = (i % 3).Equals(0);
LipsumType lipsumType = isEven ? LipsumType.Paragraphs : LipsumType.Words;
// only start with Lorem Ipsum every third call
Debug.WriteLine(LoremIpsumUtil.GetNewLipsum(lipsumType, 7, isThird).Feed.Lipsum + Environment.NewLine);
// sleep for 1 second to give the server a rest
Thread.Sleep(1000);
}
}
The main difference is that now, we use LoremIpsumUtil.GetNewLipsum(lipsumType, 7, isThird).Feed.Lipsum
.
As you can see, our properties are now Pascal cased, so they look more in line with what you'll see throughout the other .NET libraries.