Serializing JSON returning keys with dashes in them?

I would like to return JSON from my controller, which was generated from an anonymous type and contains a dash in the key names. Is it 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 serialize as follows:

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

My reason for this is that Json data will eventually become DOM node attributes, and I want to play beautifully and use the new HTML5 data attributes. I can just return { modifieddate: "3/17/2011" }and use it that way, but if I can become a little more in line with the standards, I would like to be.

I understand that if I write my own class JsonResultthat uses the WCF JSON serializer for a non-anonymous type, I can use DataMemberAttributeto accomplish this. But this is too much overhead.

I could also get the client to massage the keys for me as soon as he receives the data, but I hope to avoid this. In general, I would rather not just follow the standards than any of these workarounds.

+3
source share
2 answers

You can 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 screams to improve it by entering the result of a custom action:

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);
}
+4
source

JavaScriptSerializer, JsonResult, . , :

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

JSON .

+2

All Articles