Jun 102013
 

Recently I ran across a need for a collection of name / value objects that I could use in JSON and pass up to my MVC Web API.  The problem I ran into is that the NameValueCollection object that is in the Collections.Specialized namespace does not deserialize correctly.

After much searching into the matter I came to find out that it wasn’t the way I was using it but that it didn’t play nicely with serialization into JSON even though it is a serializable object.  When you serialize it to JSON all you receive back are the values.   This became a problem for the deserialization of the object as well.  It obviously wasn’t going to work, so after a quick trip back to the drawing board I decided to make my own set of classes to mimic a NameValueCollection object.

Now before I get to the code itself it should be noted that there are some obvious disadvantages to this method.  Because these are custom classes some of the functionality in the NameValueCollection is lost as I only kept the one thing I needed. The main object class is just a simple class with a Name and Value property that are passed in as type parameters.  Then the main collection class inherits from a List object of the simple Name Value object class.   Finally, I added a property for pulling out the value by key as you can do with the standard NameValueCollection object.

public class NameValueCollection<T1, T2> : List<NameValueObject<T1, T2>>
{
   public T2 this[T1 Name]
   {
       get
       {
           var foundObj = this.Where(n => n.Name.Equals(Name)).FirstOrDefault();
           return (foundObj != null ? foundObj.Value : default(T2));
       }
   }
}

public class NameValueObject<T1, T2>
{
   public T1 Name { get; set; }
   public T2 Value { get; set; }
}

That is the code on the server for use in my Web APIs then on the client side i’m using Knockout so I simply create an observable array and then add my objects.

this.Collection = ko.observableArray();
this.Collection.push({ Name: name, Value: value })

With that I was easily able to send that object up to my Web API and and have it deserialize correctly.  It’s not the prettiest solution, but it got the job done.  One advantage that it has over the NameValueCollection object is that I used type parameters to allow me to use whatever types I would like for my name and value objects; whereas, the NameValueCollection uses strings for both and there is no way to change it.

 

 Leave a Reply

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>