Skip to content

Commit

Permalink
ISO and JavaScript object date handling
Browse files Browse the repository at this point in the history
  • Loading branch information
johnsheehan committed Nov 22, 2009
1 parent 2871719 commit 373a0a3
Show file tree
Hide file tree
Showing 4 changed files with 99 additions and 32 deletions.
35 changes: 32 additions & 3 deletions RestSharp.Tests/JsonTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@
using Newtonsoft.Json.Linq;
using RestSharp.Deserializers;
using Xunit;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;

namespace RestSharp.Tests
{
Expand Down Expand Up @@ -90,10 +92,24 @@ public void Ignore_ReadOnly_Property_That_Exists_In_Data() {
}

[Fact]
public void Can_Deserialize_Names_With_Underscores_On_Default_Root() {
public void Can_Deserialize_Iso_Json_Dates() {
var doc = CreateIsoDateJson();
var d = new JsonDeserializer();
var bd = d.Deserialize<Birthdate>(doc);

Assert.Equal(new DateTime(1910, 9, 25, 9, 30, 25, DateTimeKind.Utc), bd.Value);
}

[Fact]
public void Can_Deserialize_JScript_Json_Dates() {
var doc = CreateJScriptDateJson();
var d = new JsonDeserializer();
var bd = d.Deserialize<Birthdate>(doc);

Assert.Equal(new DateTime(1910, 9, 25, 9, 30, 25, DateTimeKind.Utc), bd.Value);
}

private static string CreateJsonWithUnderscores() {
private string CreateJsonWithUnderscores() {
var doc = new JObject();
doc["name"] = "John Sheehan";
doc["start_date"] = new DateTime(2009, 9, 25, 0, 6, 1);
Expand Down Expand Up @@ -129,8 +145,21 @@ private static string CreateJsonWithUnderscores() {
return doc.ToString();
}

private string CreateIsoDateJson() {
var bd = new Birthdate();
bd.Value = new DateTime(1910, 9, 25, 9, 30, 25, DateTimeKind.Utc);

return JsonConvert.SerializeObject(bd, new IsoDateTimeConverter());
}

private string CreateJScriptDateJson() {
var bd = new Birthdate();
bd.Value = new DateTime(1910, 9, 25, 9, 30, 25, DateTimeKind.Utc);

return JsonConvert.SerializeObject(bd, new JavaScriptDateTimeConverter());
}

private static string CreateJson() {
private string CreateJson() {
var doc = new JObject();
doc["Name"] = "John Sheehan";
doc["StartDate"] = new DateTime(2009, 9, 25, 0, 6, 1);
Expand Down
5 changes: 5 additions & 0 deletions RestSharp.Tests/SampleClasses.cs
Original file line number Diff line number Diff line change
Expand Up @@ -72,4 +72,9 @@ public class FoeList : List<Foe>
{
public string Team { get; set; }
}

public class Birthdate
{
public DateTime Value { get; set; }
}
}
85 changes: 61 additions & 24 deletions RestSharp/Extensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
using System.Globalization;
using System.IO;
using System.Text.RegularExpressions;
using System.Collections.Generic;

namespace RestSharp
{
Expand Down Expand Up @@ -47,39 +48,75 @@ public static bool IsSubclassOfRawGeneric(this Type toCheck, Type generic) {
}

public static DateTime ParseJsonDate(this string input) {
if (input.Contains("/Date(")) {
var regex = new Regex(@"\\/Date\((\d+)(-|\+)?([0-9]{4})?\)\\/");
if (regex.IsMatch(input)) {
var matches = regex.Matches(input);
var match = matches[0];
var ms = Convert.ToInt64(match.Groups[1].Value);
var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
var dt = epoch.AddMilliseconds(ms);

// adjust if time zone modifier present
if (match.Groups[3] != null) {
var mod = DateTime.ParseExact(match.Groups[3].Value, "hhmm", CultureInfo.InvariantCulture);
if (match.Groups[2].Value == "+") {
dt = dt.Add(mod.TimeOfDay);
}
else {
dt = dt.Subtract(mod.TimeOfDay);
}
}
input = input.Replace("\n", "");
input = input.Replace("\r", "");

return dt;
}
if (input.StartsWith("\"")) {
// remove leading/trailing quotes
input = input.Substring(1, input.Length - 2);
}

if (input.Contains("/Date(")) {
return ExtractDate(input, @"\\/Date\((-?\d+)(-|\+)?([0-9]{4})?\)\\/");
}
else if (input.Contains("new Date(")) {
// TODO: implement parsing
input = input.Replace(" ", "");
// because all whitespace is removed, match against newDate( instead of new Date(
return ExtractDate(input, @"newDate\((-?\d+)*\)");
}
else if (input.Matches(@"([0-9-])*T([0-9\:]*)Z?")) {
return ParseIso8601Date(input);
}
else if (input.Matches(@"([0-9-])*T([0-9\:]*)Z")) {
// TODO: implement parsing

return default(DateTime);
}

private static DateTime ParseIso8601Date(string input) {
var formats = new string[] {
"u",
"s",
"yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'",
"yyyy-MM-ddTHH:mm:ssZ",
"yyyy-MM-dd HH:mm:ssZ",
"yyyy-MM-ddTHH:mm:ss",
"yyyy-MM-ddTHH:mm:sszzzzzz"
};

DateTime date;
if (DateTime.TryParseExact(input, formats,
CultureInfo.InvariantCulture,
DateTimeStyles.None, out date)) {
return date;
}

return default(DateTime);
}

private static DateTime ExtractDate(string input, string pattern) {
DateTime dt = DateTime.MinValue;
var regex = new Regex(pattern);
if (regex.IsMatch(input)) {
var matches = regex.Matches(input);
var match = matches[0];
var ms = Convert.ToInt64(match.Groups[1].Value);
var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
dt = epoch.AddMilliseconds(ms);

// adjust if time zone modifier present
if (match.Groups.Count > 2 && match.Groups[3] != null) {
var mod = DateTime.ParseExact(match.Groups[3].Value, "hhmm", CultureInfo.InvariantCulture);
if (match.Groups[2].Value == "+") {
dt = dt.Add(mod.TimeOfDay);
}
else {
dt = dt.Subtract(mod.TimeOfDay);
}
}

}
return dt;
}

public static bool Matches(this string input, string pattern) {
return Regex.IsMatch(input, pattern);
}
Expand Down
6 changes: 1 addition & 5 deletions RestSharp/RestRequest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ namespace RestSharp
public class RestRequest
{
public RestRequest() {
Initialize();
Parameters = new List<Parameter>();
}

public RestRequest(Method verb)
Expand All @@ -41,10 +41,6 @@ public RestRequest(string action, Method verb)
Verb = verb;
}

private void Initialize() {
Parameters = new List<Parameter>();
}

public void AddObject(object obj, params string[] whitelist) {
// automatically create parameters from object props
var type = obj.GetType();
Expand Down

0 comments on commit 373a0a3

Please sign in to comment.