Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add dateonly json convertor #6669

Merged
merged 2 commits into from
May 8, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
49 changes: 49 additions & 0 deletions src/Abp.AspNetCore/Json/DateOnlyJsonConverter.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
using Newtonsoft.Json;
using System;

namespace Abp.Json
{
public class DateOnlyJsonConverter : JsonConverter<DateOnly>
{
public override void WriteJson(JsonWriter writer, DateOnly value, JsonSerializer serializer)
{
writer.WriteValue(value.ToString("O"));
}

public override DateOnly ReadJson(
JsonReader reader,
Type objectType,
DateOnly existingValue,
bool hasExistingValue,
JsonSerializer serializer)
{
if (reader.Value == null)
{
return DateOnly.MinValue;
}

var dateValueType = reader.Value.GetType();
if (dateValueType == typeof(DateTimeOffset)) //when the object is from a property
//in POST body. When used in service,
//better to have
//options.SerializerSettings.DateParseHandling =
//Newtonsoft.Json.DateParseHandling.DateTimeOffset;
{
return DateOnly.FromDateTime(((DateTimeOffset) reader.Value).DateTime);
}

if (dateValueType == typeof(string))
{
return DateOnly.Parse((string) reader.Value); // DateOnly can parse 00001-01-01
}

if (dateValueType == typeof(DateTime)) // when the object is from a property
//in POST body from a TS client
{
return DateOnly.FromDateTime((DateTime) reader.Value);
}

throw new NotSupportedException($"Not yet support {dateValueType} in {this.GetType()}.");
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ public override void PreInitialize()
Configuration.Localization.Languages.Add(new LanguageInfo("tr", "Türkçe"));
Configuration.Localization.Languages.Add(new LanguageInfo("pt-br", "Portuguese - Brazil"));
Configuration.Localization.Languages.Add(new LanguageInfo("en-gb", "English - United Kingdom"));
Configuration.Localization.Languages.Add(new LanguageInfo("ro", "Română"));

Configuration.Localization.Sources.Add(
new DictionaryBasedLocalizationSource("AbpAspNetCoreDemoModule",
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using System;
using System.Globalization;
using Abp.Application.Services;

Expand All @@ -11,20 +12,24 @@ public CalculatePriceOutput CalculatePrice(CalculatePriceDto input)
return new CalculatePriceOutput
{
Culture = culture,
Price = input.Price.ToString()
Price = input.Price.ToString(),
OrderDate = input.OrderDate.ToString(),
};
}
}

public class CalculatePriceDto
{
public double Price { get; set; }
public DateOnly OrderDate { get; set; }
}

public class CalculatePriceOutput
{
public string Price { get; set; }

public string OrderDate { get; set; }

public string Culture { get; set; }
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ public ModelBindingAppServiceTests()
[InlineData("en", "4,242", "4242")]
[InlineData("tr", "42,42", "42,42")]
[InlineData("en-GB", "42.42", "42.42")]
[InlineData("ro", "42,42", "42,42")]
public async Task Test_Double_Binding(string culture, string inputPrice, string outputPrice)
{
var client = _factory.CreateClient();
Expand All @@ -50,5 +51,34 @@ public async Task Test_Double_Binding(string culture, string inputPrice, string
output.Result.Price.ShouldBe(outputPrice);
output.Result.Culture.ShouldBe(culture);
}


[Theory]
[InlineData("pt-BR", "2023-03-03T09:35:12.1271362+02:00", "03/03/2023")]
[InlineData("en", "2023-03-03T09:35:12.1271362+02:00", "3/3/2023")]
[InlineData("en", "2023-03-03", "3/3/2023")]
[InlineData("tr", "2023-03-03T09:35:12.1271362+02:00", "3.03.2023")]
[InlineData("en-GB", "2023-03-03T09:35:12.1271362+02:00", "03/03/2023")]
[InlineData("ro", "2023-03-03T09:35:12.1271362+02:00", "03.03.2023")]
public async Task Test_DateOnly_Binding(string culture, string inputOrderDate, string outputOrderDate)
{
var client = _factory.CreateClient();

// Arrange
client.DefaultRequestHeaders.Add(HeaderNames.AcceptLanguage, culture);
var content = new StringContent("{OrderDate: \"" + inputOrderDate + "\" }", Encoding.UTF8, "application/json");

// Act
var response = await client.PostAsync("/api/services/app/ModelBinding/CalculatePrice", content);

// Assert
response.EnsureSuccessStatusCode();

var responseContent = await response.Content.ReadAsStringAsync();
var output = JsonConvert.DeserializeObject<AjaxResponse<CalculatePriceOutput>>(responseContent);

output.Result.OrderDate.ShouldBe(outputOrderDate);
output.Result.Culture.ShouldBe(culture);
}
}
}
1 change: 1 addition & 0 deletions test/aspnet-core-demo/AbpAspNetCoreDemo/Startup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@ public IServiceProvider ConfigureServices(IServiceCollection services)

options.SerializerSettings.Converters.Add(new CultureInvariantDecimalConverter());
options.SerializerSettings.Converters.Add(new CultureInvariantDoubleConverter());
options.SerializerSettings.Converters.Add(new DateOnlyJsonConverter());
}).AddRazorRuntimeCompilation().AddOData(opts =>
{
var builder = new ODataConventionModelBuilder();
Expand Down