/// <summary> /// Converts NULL values to String.Empty in any object /// </summary> /// <param name="o"></param> public static void ConvertNullToEmptyString(object o) { Type stringType = typeof(String); var q = from n in o.GetType().GetProperties() where n.PropertyType == stringType select n; foreach (PropertyInfo p in q) if (p.GetValue(o, null) == null) p.SetValue(o, String.Empty, null); }
The above code is a little function that I wrote that converts all NULL string references in an object to String.Empty. Don’t forget to add in a Reflection using statement.
public myTestClass myTestClass() { myTestClass n = new myTestClass(); // ?Get from Database? n.string_1 = null; n.string_2 = "Hello"; // Convert null values ConvertNullToEmptyString(n); // Return the new object return n; }
/// <summary> /// Simple class /// </summary> public class myTestClass { public string string_1 { get; set; } public string string_2 { get; set; } }
This example shows how it could be used. This way, when running a JSON based webservice, the data returned van be filtered through ConvertNullToEmptyString and that will make JavaScript much happier, rather than having to deal with … “string_1” : "null, … we get a : “”, which is then immediately usable.
- Matthew