I recently created a custom static class in C# to encode, hopefully, any object it is given (or collection of objects), because I was, at the time, unaware of a native C# library that did the same thing. I am using Generics instead of System.Object because I am aware of the overhead that comes with boxing/unboxing.
After discovering System.Web.Helpers
, which had to be installed via NuGet, I discovered their methods usually take in an object
and Type
, so I assume they're using boxing/unboxing:
public static dynamic Decode(string value);
public static T Decode<T>(string value);
public static dynamic Decode(string value, Type targetType);
public static string Encode(object value);
public static void Write(object value, TextWriter writer);
Here is my code:
public static string ToJson<U, T>(U arg) where U : IEnumerable<T>
{
StringBuilder json = new StringBuilder();
json.Append(@"{""data"" : [");
foreach (var item in arg)
{// iterate through the IEnumerable
json.Append("{");
foreach (var property in typeof(T).GetProperties())
{// iterate over the properties of the class stored in the IEnumerable argument
var value = property.GetValue(item, null).ToString();
if (value == null)// make sure value is not null or empty
json.AppendFormat(@"""{0}"": """",", property.Name);
else
{
if (value.Contains("\r\n"))
{// convert the new lines into an array of strings, to be joined when read
json.AppendFormat(@"""{0}"": [""{1}""],", property.Name,
value.Replace("\"", "\\\"").Replace("\r\n", @""","""));
// can be read back by join('\n');
}
else
json.AppendFormat(@"""{0}"": ""{1}"",", property.Name,
value.Replace("\"", "\\\""));
}
}
// remove the trailing comma
json.Remove(json.Length - 1, 1);
json.Append("},");// add another row in the array (another dictionary)
}
if (json.Length > 11)
{
// remove the trailing comma
json.Remove(json.Length - 1, 1);
json.Append("]}");
}
else
// no results from sql query:
json.Replace("[", @"""none""}");
return json.ToString();
}
Is there something that I'm missing out on, or is my code not optimal/pretty?
ToJson<IEnumerable<string>, string>(new string[] { "Hello" });
throws an exception. \$\endgroup\$