Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a JSON.NET Date to String custom Converter

Tags:

Could someone tell me please how I can create a custom converter

I know I can use JSON.NET ISODateConvertor, but what I want is specific, I just want to send the value as "day/month/year" string on response.

like image 514
DevMania Avatar asked Dec 26 '11 21:12

DevMania


People also ask

What is JsonSerializerSettings?

Specifies the settings on a JsonSerializer object. Newtonsoft.Json. JsonSerializerSettings. Namespace: Newtonsoft.Json.

What is Jsonconvert DeserializeObject?

DeserializeObject<T>(String,JsonConverter[]) Deserializes the JSON to the specified . NET type using a collection of JsonConverter. DeserializeObject(String, JsonSerializerSettings) Deserializes the JSON to a .

What is Jsonconvert SerializeObject C#?

SerializeObject Method (Object, Type, JsonSerializerSettings) Serializes the specified object to a JSON string using a type, formatting and JsonSerializerSettings. Namespace: Newtonsoft.Json.


1 Answers

Something like this?

string str = JsonConvert.SerializeObject(new DateTimeClass(), new MyDateTimeConvertor());  public class DateTimeClass {     public DateTime dt;     public int dummy = 0; }  public class MyDateTimeConvertor : DateTimeConverterBase {     public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)     {         return DateTime.Parse(reader.Value.ToString());     }      public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)     {         writer.WriteValue( ((DateTime)value).ToString("dd/MM/yyyy") );     } } 
like image 152
L.B Avatar answered Sep 24 '22 01:09

L.B