JSON Webservices & Null Values from Data Objects

| No Comments | No TrackBacks

/// <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

No TrackBacks

TrackBack URL: http://www.csharpbydesign.com/cgi-bin/mt/mt-tb.cgi/21

Leave a comment

About this Entry

This page contains a single entry by Matthew M. published on July 30, 2008 9:21 PM.

ASP.NET, AJAX, and jQuery was the previous entry in this blog.

Maintaining a Blog is Hard, and So is Coding is the next entry in this blog.

Find recent content on the main index or look in the archives to find all content.