anvesh
anvesh

Reputation: 81

Convert Model class to JSON string by converting date format in .Net core c#

I am writing web api in C# .net core. Need to convert my model class to json string.

My class as

public class InputModel
{
public string Id{get; set;}
public DateTime? ArrivalDate{get; set;}
public string origin{get; set;}
}

inputModel.origin = string.Empty; Currently I am converting as

string Result = System.Text.Json.JsonSerializer.Serialize(inputModel, new JsonSerializerOptions { IgnoreNullValues = true} );

My Current Result is

Result =  {
     "Id":"54"
     "ArrivalDate": "2020-07-26T00:00:00+00:00"
 }

My Desired Result is

Result =  {
         "Id":"54"
         "ArrivalDate": "2020-07-26 00:00" --> "yyyy-MM-dd hh:mm"
     }

I am aware that my current JsonSerializer not doing anything to convert the dateformat any input are much appreciated

Upvotes: 2

Views: 1417

Answers (2)

anvesh
anvesh

Reputation: 81

I achieved my desired date format type in json string by

public class CustomDateTimeConverter : JsonConverter<DateTime>
    {
        public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
        {
            Debug.Assert(typeToConvert == typeof(DateTime));
            return DateTime.Parse(reader.GetString());
        }

        public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options)
        {
            writer.WriteStringValue(value.ToString("dd'-'MM'-'yyyy HH':'mm"));
        }
    }

Calling our converter class at the code level as below

JsonSerializerOptions options = new JsonSerializerOptions();
                    options.Converters.Add(new CustomDateTimeConverter());
                    options.IgnoreNullValues = true;
                    string Result = System.Text.Json.JsonSerializer.Serialize(inputModel, options );

With this I could able to convert the Default Date format....

Upvotes: 0

Sh.Imran
Sh.Imran

Reputation: 1033

It cab be achieved simply by doing serialization with Newtonsoft.Json library. In this library, there is an overload method of serialization in which DateTime format can be mentioned. Its given below:

string Result = JsonConvert.SerializeObject(inputModel, new IsoDateTimeConverter() { DateTimeFormat= "yyyy-MM-dd HH:mm" });

The data would be containing with the ArrivalDate in the required format.

Upvotes: 1

Related Questions