I am developing an API to expose some data using ASP.NET Web API.
In one of the API, the client wants us to expose the date in yyyy-MM-dd format. I don't want to change the global settings (e.g. GlobalConfiguration.Configuration.Formatters.JsonFormatter) for that since it is very specific to this client. And I do developing that in a solution for multiple clients.
One of the solution that I could think of is to create a custom JsonConverter and then put that to the property I need to do the custom formatting
e.g.
class ReturnObjectA
{
[JsonConverter(typeof(CustomDateTimeConverter))]
public DateTime ReturnDate { get;set;}
}
Just wondering if there is some other easy way of doing that.
You are on the right track. Since you said you can't modify the global settings, then the next best thing is to apply the JsonConverter attribute on an as-needed basis, as you suggested. It turns out Json.Net already has a built-in IsoDateTimeConverter that lets you specify the date format. Unfortunately, you can't set the format via the JsonConverter attribute, since the attribute's sole argument is a type. However, there is a simple solution: subclass the IsoDateTimeConverter, then specify the date format in the constructor of the subclass. Apply the JsonConverter attribute where needed, specifying your custom converter, and you're ready to go. Here is the entirety of the code needed:
class CustomDateTimeConverter : IsoDateTimeConverter
{
public CustomDateTimeConverter()
{
base.DateTimeFormat = "yyyy-MM-dd";
}
}
If you don't mind having the time in there also, you don't even need to subclass the IsoDateTimeConverter. Its default date format is yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFFK (as seen in the source code).
You could use this approach:
public class DateFormatConverter : IsoDateTimeConverter
{
public DateFormatConverter(string format)
{
DateTimeFormat = format;
}
}
And use it this way:
class ReturnObjectA
{
[JsonConverter(typeof(DateFormatConverter), "yyyy-MM-dd")]
public DateTime ReturnDate { get;set;}
}
The DateTimeFormat string uses the .NET format string syntax described here: https://learn.microsoft.com/en-us/dotnet/standard/base-types/custom-date-and-time-format-strings
It can also be done with an IsoDateTimeConverter instance, without changing global formatting settings:
string json = JsonConvert.SerializeObject(yourObject,
new IsoDateTimeConverter() { DateTimeFormat = "yyyy-MM-dd HH:mm:ss" });
This uses the JsonConvert.SerializeObject overload that takes a params JsonConverter[] argument.
Also available using one of the serializer settings overloads:
var json = JsonConvert.SerializeObject(someObject, new JsonSerializerSettings() { DateFormatString = "yyyy-MM-ddThh:mm:ssZ" });
Or
var json = JsonConvert.SerializeObject(someObject, Formatting.Indented, new JsonSerializerSettings() { DateFormatString = "yyyy-MM-ddThh:mm:ssZ" });
Overloads taking a Type are also available.
There is another solution I've been using. Just create a string property and use it for json. This property wil return date properly formatted.
class JSonModel {
...
[JsonIgnore]
public DateTime MyDate { get; set; }
[JsonProperty("date")]
public string CustomDate {
get { return MyDate.ToString("ddMMyyyy"); }
// set { MyDate = DateTime.Parse(value); }
set { MyDate = DateTime.ParseExact(value, "ddMMyyyy", null); }
}
...
}
This way you don't have to create extra classes. Also, it allows you to create diferent data formats. e.g, you can easily create another Property for Hour using the same DateTime.
With below converter
public class CustomDateTimeConverter : IsoDateTimeConverter
{
public CustomDateTimeConverter()
{
DateTimeFormat = "yyyy-MM-dd";
}
public CustomDateTimeConverter(string format)
{
DateTimeFormat = format;
}
}
Can use it with a default custom format
class ReturnObjectA
{
[JsonConverter(typeof(CustomDateTimeConverter))]
public DateTime ReturnDate { get;set;}
}
Or any specified format for a property
class ReturnObjectB
{
[JsonConverter(typeof(CustomDateTimeConverter), "dd MMM yy")]
public DateTime ReturnDate { get;set;}
}
public static JsonSerializerSettings JsonSerializer { get; set; } = new JsonSerializerSettings()
{
DateFormatString= "yyyy-MM-dd HH:mm:ss",
NullValueHandling = NullValueHandling.Ignore,
ContractResolver = new LowercaseContractResolver()
};
Hello,
I'm using this property when I need set JsonSerializerSettings
Some times decorating the json convert attribute will not work ,it will through exception saying that "2010-10-01" is valid date. To avoid this types i removed json convert attribute on the property and mentioned in the deserilizedObject method like below.
var addresss = JsonConvert.DeserializeObject<AddressHistory>(address, new IsoDateTimeConverter { DateTimeFormat = "yyyy-MM-dd" });
Related
I had to generate some classes from an xsd file. The classes and properties are generated correct with xml serialization annotation. The problem is that the decimal properties of a class are serialized with Newtonsoft.Json even are not populated. I would like to serialize only the decimal properties that are properly populated. Amount is part of SaleMessage
For example:
class Amount
{
[System.Xml.Serialization.XmlAttributeAttribute()]
public decimal RequestedAmount;
[System.Xml.Serialization.XmlAttributeAttribute()]
public decimal CashBackAmount;
[System.Xml.Serialization.XmlAttributeAttribute()]
public decimal TipAmount;
}
//Usage
var amount = new Amount()
{
RequestedAmount = 12.0
}
Using this structure it will always serialize all the properties
like this
{"RequestedAmount":12.0,"CashBackAmount":0.0,"TipAmount":0.0}
Which is not the expected behaviour.
The question is how can I modify the serialization to not parse the not set properties
static string Serialize(SaleMessage saleMessage)
{
var serialize= JsonConvert.SerializeObject(saleToPoiMessage,
new StringEnumConverter(),
new IsoDateTimeConverter() { DateTimeFormat = DateTimeFormat });
return serialize;
}
Any help is appreciated :)
You can set the DefaultValueHandling setting to Ignore to suppress serialization of values that are equal to their default value.
var settings = new JsonSerializerSettings
{
Converters = new List<JsonConverter>
{
new StringEnumConverter(),
new IsoDateTimeConverter() { DateTimeFormat = DateTimeFormat }
},
DefaultValueHandling = DefaultValueHandling.Ignore
};
var json = JsonConvert.SerializeObject(saleMessage, settings);
Fiddle: https://dotnetfiddle.net/o32k0U
Since it's of type decimal primitive it will have some value by default. I think you need to implement the serializer utility Newtonsoft.Json uses - on your own. Where you will not include the decimal values of 0.0 (if this suits the business logic).
Another option is not to use the primitive class and then set up the property of removing null values while serializing. I believe you can set up this config parameter in Newtonsoft.
Check this: https://www.newtonsoft.com/json/help/html/CustomJsonConverter.htm
In my case I changed the primitive types to nullable.
public decimal? CashBackAmount {get; set;}
This worked for me. I prefer the #Brian Rogers answer. :)
I have something like:
[DataContract]
DateTime date;
However, I have specific format of my date: 20170403. How to force WCF serializer to serialize such format ? At this moment it returns validation error. How to do it ?
DataContractSerializer is going to follow the expected XML date format rules for dates, so if the other end isn't expecting that: you simply can't use a date. You'll have to expose it as a string instead:
public DateTime Date {get;set;} // note no serialization attribs
[DataMember(Name="date")]
public string DateString {
get { return Date.WhateverFormattingCodeYouWantHere(); }
set { Date = value.WhateverParsingCodeYouWantHere(); }
}
[Serializable]
[DataContract(IsReference = true)]
public className{
[DataMember]
DateTime date;
}
Hope this will help
I've created a C# class with a static method that convert's any object to a JSON object. I've used JavaScriptSerializar for this. Here is my code
public class JS
{
public static string GetJSON(object obj)
{
JavaScriptSerializer js = new JavaScriptSerializer();
string retJSON = js.Serialize(obj);
return retJSON;
}
}
I've another class that have only two property, Date & Remark. Here is my class
public class RemarkData
{
public DateTime Date { set; get; }
public string Remark { set; get; }
}
Now, I'm converting a object of the RemarkData class into JSON using following code
JS.GetJSON(objRemarkData);
Here is the output I'm getting
{"Date":"/Date(1389403352042)/","Remark":"Sme Remarks"}
Here is the output that I need
{"Date":1389403352042,"Remark":"Some Remarks"}
What should I do tho get that kind of output? Any help ?
double ticks = Math.Floor(objRemarkData.Date.ToUniversalTime()
.Subtract(new DateTime(1970, 1, 1))
.TotalMilliseconds);
var newob = new { Date =ticks, Remark = objRemarkData.Remark};
JS.GetJSON(newob);
You could try JSON.NET, it serializes Date into ISO string.
public class JS
{
public static string GetJSON(object obj)
{
string retJSON = JsonConvert.SerializeObject(obj);
return retJSON;
}
}
Actually, you can use it directly, don't need to wrap inside another function.
This is also how asp.net web api serializes date objects. For more information why ISO string is a good choice, check out this link http://www.hanselman.com/blog/OnTheNightmareThatIsJSONDatesPlusJSONNETAndASPNETWebAPI.aspx
This long number is "milliseconds since epoch". We can convert this to normal javascript date by using the following snippet as explained in another so post Converting .NET DateTime to JSON
var d = new Date();
d.setTime(1245398693390);
document.write(d);
One can also use a nice library from http://blog.stevenlevithan.com/archives/date-time-format with the following snippet ..
var newDate = dateFormat(jsonDate, "dd/mm/yyyy h:MM TT");
I would like to serialize my date to be in a specific format but I can't get my act together.
I tried building a nice little class but the output gets wrapped in quotes, which doesn't work.
I'd like the JSON to look like this...
{
date : new Date(2013, 8, 30)
}
but I get this...
{
date: "new Date(2013, 8, 30)"
}
my class
public class DateCell : ChartCell
{
[JsonIgnore]
public DateTime Value { get; set; }
[JsonProperty(PropertyName = "date")]
public override object DataValue
{
get
{
return string.Format("new Date({0}, {1}, {2})", this.Value.Year, this.Value.Month - 1, this.Value.Day);
}
}
}
There's a difference between a JavaScript Object and JSON. What you described might be valid in a JavaScript object, but it is not valid JSON. JSON does not allow the representation that you are asking for.
In JSON a value can only be one of the following:
A string, such as "abc"
A number, such as 123 or -12.34
A literal value of true, false, or null
An array of other valid values, such as [1,"a",true]
Another JSON object, such as { a: 1, b: "abc" }
It cannot just be a JavaScript Object, or any other arbitrary JavaScript. See the spec at json.org.
Passing a Date object constructor would not make any sense, as JSON is a general purposed serialization format, and Date is a JavaScript native class. How would you expect non-JavaScript code to interpret this?
While there is no specific date or time format defined by the JSON standard, the de facto standard is the ISO 8601 format. Your DateTime would look something like "2013-09-30T00:00:00". There are other ways to serialize a date, but they are not as uniform or popular.
In JSON.Net, the ISO 8601 format is the default. So you don't need to do anything special other than just to serialize your object with its original properties.
public class DateCell : ChartCell
{
public DateTime Value { get; set; }
}
UPDATE
Since you said in comments that you are passing this to Google Charts, it appears from their reference that they are using a nonstandard format that looks like the Date constructor, but has omitted the new keyword. Why they do this, I'm not sure, but you should be able to modify your original code as follows:
public class DateCell : ChartCell
{
[JsonIgnore]
public DateTime Value { get; set; }
[JsonProperty(PropertyName = "date")]
public override object DataValue
{
get
{
return string.Format("Date({0},{1},{2})", this.Value.Year, this.Value.Month - 1, this.Value.Day);
}
}
}
I'm xml-serializing a object with a large number of properties and I have two properties with DateTime types. I'd like to format the dates for the serialized output. I don't really want to implement the IXmlSerializable interface and overwrite the serialization for every property. Is there any other way to achieve this?
(I'm using C#, .NET 2)
Thanks.
For XML serialization you would have to implement IXmlSerializable and not ISerializable.
However you can workaround this by using a helper property and by marking the DateTime properties with the XmlIgnore attribute.
public class Foo
{
[XmlIgnore]
public DateTime Bar { get; set; }
public string BarFormatted
{
get { return this.Bar.ToString("dd-MM-yyyy"); }
set { this.Bar = DateTime.ParseExact(value, "dd-MM-yyyy", null); }
}
}
You can use a wrapper class/struct for DateTime that overrides ToString method.
public struct CustomDateTime
{
private readonly DateTime _date;
public CustomDateTime(DateTime date)
{
_date = date;
}
public override string ToString()
{
return _date.ToString("custom format");
}
}