views:

187

answers:

4

I have an IEnumerable list of date/value pairs that I am returning as a Json list to flot. However, when I call JsonResult(), the result looks like this:

[{"Date":date1, "Value":value1}, {"Date":date2, "Value":value2}...]

Flot is expecting

[[date1, value1], [date2, value2]...]

Is there any simple way to get the MVC framework to output objects like this or do I need to write my own seralizer / StringBuffer code? For that matter I don't even need to output the field names, just the values themselves.

+1  A: 

Your best bet is to write it yourself, but it is a trivial exercise to do.

In my mind, is it worth spending on hour looking for a way to do it, when you can spend 10 minutes and just do the serialization yourself.

James Black
I figured that with so many Helpers in MVC there might be an option to tweak somewhere :)
Jedidja
+1  A: 

It sounds like you just need to return a string like this:

var builder = new StringBuilder();
builder.Append("[");
foreach (var item in listOfDateTimes)
    builder.AppendFormat("[{0}, {1}], ", item.Key, item.Value);
var result = builder.ToString().TrimEnd(new char[]{',',' '}) + "]";
return result;
Joseph
builder.AppendFormat in case anyone tries to copy/paste this code later :)
Jedidja
@jedidja Thanks for the catch, my air code is never perfect =P
Joseph
Also for future reference, I ended up returning ContentResult from the method. Trying to return Json() of a string leaves it in quotes and flot is looking for an array. return Content(result, "json")
Jedidja
A: 

You might want to checkout JSON.Net

I believe it may give you the result you are looking for.

Slee
+1  A: 

Are these date/value pairs type of System.Web.UI.Pair? If so, you can do this ;

return Json(yourIEnumerable.Select(x => new[] { x.First, x.Second }).ToArray());

It returns the way you want it to be ;

[["\/Date(1255686550232)\/","foo"],["\/Date(1255686550232)\/","bar"]]

Even if they're not type of System.Web.UI.Pair, I'm sure you get the idea.

çağdaş