views:

428

answers:

1

Hi folks,

i've got a really simple POCO (business) object which I'm returning to the client as some json, using ASP.NET MVC.

eg. (please ignore the lack of error checking, etc).

public JsonAction Index()
{
    Foo myFoo = MyService();
    return Json(myFoo);
}

kewl. Now, this object includes following public properties...

public class Foo
{
    public decimal Score { get; set; }
    public Dictionary<string, string> KeyValues { get; set; }
}

Now when the object is serialized into json, the decimal score has a precision of 7 (and i'm after a precision of 2) and the KeyValues might be null. If it's null, the the json looks like this...

"KeyValues" : null

I was hoping to have the KeyValues NOT be included in the json, if it's null.

Are there any tricks to helping format this json output? Or do i need to manually do this .. make my own string .. then return it as .. i donno .. a ContentAction? (eeks).

please help!

+1  A: 

The ASP.Net MVC Json() method uses the JavascriptSerializer internally to do it's encoding. There are some options to control the serialization of your classes by creating and registering your own JavascriptConverter objects.

womp
gotcha. so i need to provide my own code to tell the serializer HOW my poco's need to be serialized and/or deserialized.
Pure.Krome
Yeah unfortunately. Basically this amounts to providing custom Serialize() and Deserialize() methods that iterate over your object properties and add their values to the dictionary to be JSON'd. You would skip the null values. A fancy way of constructing your own strings really ;)
womp
No chance to ask for any blog posts / examples? for shi+s and giggs?
Pure.Krome
I think the examples on the documentation page that I linked are pretty good. Where it is creating the "text" and "value" items to put into the dictionary, you would put in "propertyname" and "propertyvalue". If I get some time later I'll try it out myself but don't count on it ;)
womp
Unfortunately, you can't add a converter to the serializer that the JSONResult uses. Therefore you'll need to create your own JavaScriptSerializer and register your converter using .RegisterConverters(). Create a ContentResult and set the Content property to your object, serialized with you serializer. Set the ContentType to "application/json" and then return the ContentResult. :-)
Russell Giddings