恶梦护士 asa_噩梦就是JSON日期。 另外,JSON.NET和ASP.NET Web API
惡夢護士 asa
Ints are easy. Strings are mostly easy. Dates? A nightmare. They always will be. There's different calendars, different formats. Did you know it's 2004 in the Ethiopian Calendar? Yakatit 26, 2004, in fact. I spoke to a German friend once about how much 9/11 affected me and he said, "yes, November 9th was an amazing day in Germany, also."
整數(shù)很容易。 字符串通常很容易。 日期? 一個噩夢。 他們永遠都是。 有不同的日歷,不同的格式。 您知道埃塞俄比亞日歷中的2004年嗎? 實際上,Yakatit 26,2004。 我曾經(jīng)和一位德國朋友談過9/11對我有多大影響,他說:“是的, 11月9日在德國也是令人興奮的一天。”
Dates are hard.
日期很難。
If I take a simple model:
如果我采用一個簡單的模型:
public class Post{
public int ID { get; set; }
[StringLength(60)][Required]
public string Title { get; set; }
[StringLength(500)]
[DataType(DataType.MultilineText)]
[AllowHtml]
public string Text { get; set; }
public DateTime PublishedAt { get; set; }
}
And I make a quick ASP.NET Web API controller from VS11 Beta (snipped some stuff for simplicity):
我從VS11 Beta中制作了一個快速的ASP.NET Web API控制器(為簡單起見,刪除了一些內(nèi)容):
public class PostAPIController : ApiController{
private BlogContext db = new BlogContext();
// GET /api/post
public IEnumerable<Post> Get()
{
return db.Posts.ToList();
}
// GET /api/post/5
public Post Get(int id)
{
return db.Posts.Where(p => p.ID == id).Single();
}
...snip...
}
And hit /api/post with this Knockout View Model and jQuery.
然后使用此Knockout視圖模型和jQuery命中/ api / post。
$(function () {$("#getPosts").click(function () {
// We're using a Knockout model. This clears out the existing posts.
viewModel.posts([]);
$.get('/api/PostAPI', function (data) {
// Update the Knockout model (and thus the UI)
// with the posts received back
// from the Web API call.
viewModel.posts(data);
});
});
viewModel = {
posts: ko.observableArray([])
};
ko.applyBindings(viewModel);
});
And this super basic template:
而這個超級基本模板:
<li class="comment"><header>
<div class="info">
<strong><span data-bind="text: Title"></span></strong>
</div>
</header>
<div class="body">
<p data-bind="date: PublishedAt"></p>
<p data-bind="text: Text"></p>
</div>
</li>
I am saddened as the date binding doesn't work, because the date was serialized by default like this. Here's the JSON on the wire.
我為日期綁定不起作用而感到難過,因為默認情況下日期是這樣序列化的。 這是在線上的JSON。
[{"ID": 1,
"PublishedAt": "\/Date(1330848000000-0800)\/",
"Text": "Best blog post ever",
"Title": "Magical Title"
}, {
"ID": 2,
"PublishedAt": "\/Date(1320825600000-0800)\/",
"Text": "No, really",
"Title": "You rock"
}]
Eek! My eyes! That's milliseconds since the beginning of the Unix Epoch WITH a TimeZone. So, converting in PowerShell looks like:
ek! 我的眼睛! 從Unix紀(jì)元以TimeZone開始的毫秒數(shù)。 因此,在PowerShell中進行轉(zhuǎn)換看起來像:
PS C:\> (new-object DateTime(1970,1,1,0,0,0,0)).AddMilliseconds(1330848000000).AddHours(-8)Sunday, March 04, 2012 12:00:00 AM
Yuck. Regardless,? it doesn't bind with KnockoutJS either. I could add a bindingHandler for dates like this:
uck 無論如何,它也不與KnockoutJS綁定。 我可以為這樣的日期添加bindingHandler:
ko.bindingHandlers.date = {init: function (element, valueAccessor, allBindingsAccessor, viewModel) {
var jsonDate = valueAccessor();
var value = new Date(parseInt(jsonDate.substr(6)));
var ret = value.getMonth() + 1 + "/" + value.getDate() + "/" + value.getFullYear();
element.innerHTML = ret;
},
update: function (element, valueAccessor, allBindingsAccessor, viewModel) {
}
};
That works, but it's horrible and I hate myself. It's lousy parsing and it doesn't even take the TimeZone into consideration. This is a silly format for a date to be in on the wire.
那行得通,但這太可怕了,我討厭自己。 這很糟糕,而且甚至沒有考慮到TimeZone。 這是一種愚蠢的格式,可以將日期插入網(wǎng)絡(luò)。
I was talking to some folks on Twitter in the last few days and said that all this is silly and JSON dates should be ISO 8601, and we should all move on. James Newton-King the author of JSON.NET answered by making ISO 8601 the default in his library. We on the web team will be including JSON.NET as the default JSON Serializer in Web API when it releases, so that'll be nice.
最近幾天,我在Twitter上與一些人交談,說這一切很愚蠢,JSON日期應(yīng)為ISO 8601,我們應(yīng)該繼續(xù)前進。 JSON.NET的作者James Newton-King通過將ISO 8601設(shè)為其庫中的默認值來回答。 Web團隊發(fā)布時,將在Web API中將JSON.NET作為默認的JSON序列化程序包括在內(nèi),這樣會很不錯。
I mentioned this to Raffi from Twitter a few weeks back and he agreeds. He tweeted back to me
幾周前,我在Twitter上向拉菲提到了這一點,他同意了。 他發(fā)了推文給我
@shanselman if (when) we ship a v2 API, you can almost bet its going to be 8601 /cc @twitterAPI @johnsheehan
— Raffi Krikorian (@raffi)@ shanselman如果(當(dāng)我們提供)v2 API時,您幾乎可以打賭它將變?yōu)?601 / cc @ twitterAPI @ johnsheehan
— Raffi Krikorian(@raffi) March 4, 20122012年3月4日@twitterAPI does (ruby strings)." What does that look like? Well, see for yourself: https://www.twitter.com/statuses/public_timeline.json in a random public timeline tweet...snipped out the boring stuff...
@ twitterAPI會(Ruby字符串)。”這看起來像什么?好吧,親自看看: https : //www.twitter.com/statuses/public_timeline.json在隨機的公共時間軸推文中……窺探到了無聊的東西...
{"id_str": "176815815037952000",
"user": {
"id": 455349633,
...snip...
"time_zone": null
},
"id": 176815815037952000,
"created_at": "Mon Mar 05 23:45:50 +0000 2012"
}
Yes, so DON'T do it that way. Let's just do it the JavaScript 1.8.5/ECMASCript 5th way and stop talking about it. Here's Firefox, Chrome and IE.
是的,所以不要那樣做。 讓我們以第五種方式執(zhí)行JavaScript 1.8.5 / ECMASCript,然后停止談?wù)撍?這是Firefox,Chrome和IE。
We're going to do this by default in ASP.NET Web API when it releases. (We aren't doing this now in Beta) You can see how to swap out the serializer to JSON.NET on Henrik's blog. You can also check out the Thinktecture.Web.Http convenience methods that bundles some useful methods for ASP.NET Web API.
默認情況下,我們將在ASP.NET Web API發(fā)布時執(zhí)行此操作。 (我們現(xiàn)在不在Beta版中進行此操作),您可以在Henrik的博客上看到如何將序列化器換成JSON.NET 。 您還可以簽出Thinktecture.Web.Http便捷方法,該方法捆綁了ASP.NET Web API的一些有用方法。
Today with the Beta, I just need to update my global.asax and swap out the JSON Formatter like this (see Henrik's blog for the full code):
今天,使用Beta版,我只需要更新我的global.asax并換成這樣的JSON Formatter(有關(guān)完整代碼,請參見Henrik的博客):
// Create Json.Net formatter serializing DateTime using the ISO 8601 formatJsonSerializerSettings serializerSettings = new JsonSerializerSettings();
serializerSettings.Converters.Add(new IsoDateTimeConverter());
GlobalConfiguration.Configuration.Formatters[0] = new JsonNetFormatter(serializerSettings);
When we ship, none of this will be needed as it should be the default which is much nicer. JSON.NET will be the default serializer AND Web API will use ISO 8601 on the wire as the default date format for JSON APIs.
當(dāng)我們發(fā)貨時,不需要任何這些,因為它應(yīng)該是默認值,這樣更好。 JSON.NET將是默認的序列化器,并且Web API將在線使用ISO 8601作為JSON API的默認日期格式。
Hope this helps.
希望這可以幫助。
Sponsor: Big thanks to DevExpress for sponsoring this last week's feed. There is no better time to discover DevExpress. Visual Studio 11 beta is here and DevExpress tools are ready! Experience next generation tools, today.
贊助商:非常感謝DevExpress贊助了上周的feed。 沒有更好的時間來發(fā)現(xiàn)DevExpress。 Visual Studio 11 beta已發(fā)布,DevExpress工具已準(zhǔn)備就緒! 立即體驗下一代工具。
翻譯自: https://www.hanselman.com/blog/on-the-nightmare-that-is-json-dates-plus-jsonnet-and-aspnet-web-api
惡夢護士 asa
總結(jié)
以上是生活随笔為你收集整理的恶梦护士 asa_噩梦就是JSON日期。 另外,JSON.NET和ASP.NET Web API的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【 WinForm】全屏截图,控件截图,
- 下一篇: 菜鸟LeetCode-动态规划