Json.NET初试

处理Json时候一直都是用微软自家的JavaScriptSerializer,但转换时间的格式是微软给定的格式,如
{date:"\/Date(1234656000000)\/"}

送到client时用javascript再转换成ISO 8601标准的时间格式。

后来发现了Json.NET,它转换时间默认就是使用ISO 8601标准的,有需要还可以设为javascript的时间格式或设回微软默认格式。

官方例子:

public class LogEntry
{
  public string Details { get; set; }
  public DateTime LogDate { get; set; }
}

public void WriteJsonDates()
{
  LogEntry entry = new LogEntry
  {
    LogDate = new DateTime(2009, 2, 15, 0, 0, 0, DateTimeKind.Utc),
    Details = "Application started."
  };

  // default as of Json.NET 4.5
  string isoJson = JsonConvert.SerializeObject(entry);
  // {"Details":"Application started.","LogDate":"2009-02-15T00:00:00Z"}

  JsonSerializerSettings microsoftDateFormatSettings = new JsonSerializerSettings
  {
    DateFormatHandling = DateFormatHandling.MicrosoftDateFormat
  };
  string microsoftJson = JsonConvert.SerializeObject(entry, microsoftDateFormatSettings);
  // {"Details":"Application started.","LogDate":"\/Date(1234656000000)\/"}

  string javascriptJson = JsonConvert.SerializeObject(entry, new JavaScriptDateTimeConverter());
  // {"Details":"Application started.","LogDate":new Date(1234656000000)}
}



Json.NET使用JsonConvert类的SerializeObject方法序列化实体为Json,比JavaScriptSerializer要方便得多。

你可能感兴趣的:(Json.Net)