i am experimenting with backbone javascript after seeing the Tekpub MVC3 screencasts by Rob Connery
i like his Massive database access, but as soon as it is getting a bit more complex than a video can possibly show you.
i added extra fields to my database, being datetime
fields. however, this javascript serializer, converts them into strings
public string toJson(dynamic content) {
var serializer = new JavaScriptSerializer();
serializer.RegisterConverters(new JavaScriptConverter[] { new ExpandoObjectConverter() });
var json = serializer.Serialize(content);
return json.ToString();
}
this makes a datetime from this: {19/10/2011 1:58:27}
into this: "19/10/2011"
(*values taken from the quickwatch window on runtime..., basicly comes down to a loss in precision and it now being a basic string.
after backbone pushes that back to the server (on a model.save() call), i try to update the model like Rob does:
[HttpPut]
public ActionResult Edit()
{
var model = SqueezeJson();
model.UpdatedAt = DateTime.Now;
_movies.Update(model, model.Id);
return CmoJSON(model);
}
for the SqueezeJson function, check his source
resulting in an error like this:
Arithmetic overflow error converting expression to data type datetime.
i kind of expected this to happen since i noticed the dates being dumped into strings, i had no idea how it would go back into a date time using massive.
has anyone worked with massive and dates, in a context like this (serializing to and from json)? i know the problem isn't necessarily massive itself, it's the json serializiation that dumbs it down into a string with loss of data, and doesn't return it to a proper date.
but still, maybe someone has a better way of doing this... any idea's are welcome...
I have encountered the same question with you.
You can change Serialize method in ExpandoObjectConverter like:
public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)
{
ExpandoObject expando = (ExpandoObject) obj;
if(expando!=null)
{
Dictionary<string,object> result = new Dictionary<string, object>();
foreach (KeyValuePair<string, object> item in expando)
{
var value = item.Value ?? "";
if (value is DateTime)
result.Add(item.Key, ((DateTime) value).ToString("yyyy.MM.dd"));
else
{
result.Add(item.Key, value.ToString());
}
}
return result;
}
return new Dictionary<string, object>();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.