Question

I would like to return JSON from my controller which was generated from an anonymous type and contains dashes in the key names. Is this possible?

So if I have this:

public ActionResult GetJSONData() {
    var data = new { DataModifiedDate = myDate.ToShortDateString() };
    return Json(data);
}

On the client side I would like it to arrive serialized like this:

{ "data-modified-date" : "3/17/2011" }

My reason for wanting this is this Json data will ultimately become attributes on a DOM node, and I want to play nice and use the new HTML5 data attributes. I can just return { modifieddate: "3/17/2011" } and use it this way, but if I can become that little bit more conforming to standards I'd like to be.

I understand if I write my own JsonResult class that uses the WCF JSON Serializer on a non anonymous type, I can use theDataMemberAttribute to accomplish this. But that's a lot of overhead for such a simple desire.

I could also have the client massage the keys for me once it receives the data, but I'm hoping to avoid that too. All in all I'd rather just not follow standards than either of these workarounds.

Was it helpful?

Solution

You could use Json.NET and have full control over property names:

public ActionResult GetJSONData() 
{
    var obj = new JObject();
    obj["data-modified-date"] = myDate.ToShortDateString();
    var result = JsonConvert.SerializeObject(obj);
    return Content(result, "application/json");
}

Obviously this code is screaming to be improved by introducing a custom action result:

public class JsonNetResult : ActionResult
{
    private readonly JObject _jObject;
    public JsonNetResult(JObject jObject)
    {
        _jObject = jObject;
    }

    public override void ExecuteResult(ControllerContext context)
    {
        var response = context.HttpContext.Response;
        response.ContentType = "application/json";
        response.Write(JsonConvert.SerializeObject(_jObject));
    }
}

and then:

public ActionResult GetJSONData() 
{
    var obj = new JObject();
    obj["data-modified-date"] = myDate.ToShortDateString();
    return new JsonNetResult(obj);
}

OTHER TIPS

I found the JavaScriptSerializer that JsonResult uses has a special case for Dictionaries. So if you just do:

var data = new Dictionary<string, string> 
{
     { "data-modified-date", myDate.ToShortDateString() }
};

Then the resulting JSON is in the desired format.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top