views:

556

answers:

3

Is there a way to control the JSON output of JsonResult with attributes, similar to how you can use XmlElementAttribute and its bretheren to control the output of XML serialization?

For example, given the following class:

public class Foo
{
    [SomeJsonSerializationAttribute("bar")]
    public String Bar { get; set; }

    [SomeJsonSerializationAttribute("oygevalt")]
    public String Oygevalt { get; set; }
}

I'd like to then get the following output:

{ bar: '', oygevalt: '' }

As opposed to:

{ Bar: '', Oygevalt: '' }
+1  A: 

Check out the newly released Sierra: http://kohari.org/2009/08/10/siesta-painless-rest-via-asp-net-mvc/

Jarrett Meyer
This looks promising (and interesting!), but I was hoping for something already baked in. Any way to get the existing serializer to respect the DataContract attributes?
Daniel Schaffer
+3  A: 

I wanted something a bit more baked into the framework than what Jarrett suggested, so here's what I did:

JsonDataContractActionResult:

public class JsonDataContractActionResult : ActionResult
{
    public JsonDataContractActionResult(Object data)
    {
        this.Data = data;
    }

    public Object Data { get; private set; }

    public override void ExecuteResult(ControllerContext context)
    {
        var serializer = new DataContractJsonSerializer(this.Data.GetType());
        String output = String.Empty;
        using (var ms = new MemoryStream())
        {
            serializer.WriteObject(ms, this.Data);
            output = Encoding.Default.GetString(ms.ToArray());
        }
        context.HttpContext.Response.ContentType = "application/json";
        context.HttpContext.Response.Write(output);
    }
}

JsonContract() method, added to my base controller class:

    public ActionResult JsonContract(Object data)
    {
        return new JsonDataContractActionResult(data);
    }

Sample Usage:

    public ActionResult Update(String id, [Bind(Exclude="Id")] Advertiser advertiser)
    {
        Int32 advertiserId;
        if (Int32.TryParse(id, out advertiserId))
        {
            // update
        }
        else
        {
            // insert
        }

        return JsonContract(advertiser);
    }
Daniel Schaffer
The awesome part about MVC is how easy this stuff is to write. You can put together some really sophisticated solutions quite quickly!
Jarrett Meyer
Indeed it is! I don't plan on ever looking back to WebForms.
Daniel Schaffer
+2  A: 

Easy answer: the DataContractJsonSerializer should respect the [DataContract] and [DataMember] attributes in the System.Runtime.Serialization namespace of the BCL.

Nate Kohari