WCF DataMember DateTime Serializing Format - json

I have a working WCF service which used JSON as its RequestFormat and ResponseFormat.
[ServiceContract]
public interface IServiceJSON
{
[OperationContract]
[WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
MyClassA echo(MyClassA oMyObject);
}
[DataContract]
public class MyClassA
{
[DataMember]
public string message;
[DataMember]
public List<MyClassB> myList;
public MyClassA()
{
myList = new List<MyClassB>();
}
}
[DataContract]
public class MyClassB
{
[DataMember]
public int myInt;
[DataMember]
public double myDouble;
[DataMember]
public bool myBool;
[DataMember]
public DateTime myDateTime;
}
The myDateTime property of class MyClassB is of type DateTime. This is being serialized to the following format: "myDateTime":"/Date(1329919837509+0100)/"
The client I need to communicate with can not deal with this format. It requires it to be a more conventional format like for example: yyyy-MM-dd hh:mm:ss
Is it somehow possible to add this to the DataMember attribute? Like so:
[DataMember format = “yyyy-MM-dd hh:mm:ss”]
public DateTime myDateTime;
Thanks in advance!

Here's an example of the already checked answer...
[DataContract]
public class ProductExport
{
[DataMember]
public Guid ExportID { get; set; }
[DataMember( EmitDefaultValue = false, Name = "updateStartDate" )]
public string UpdateStartDateStr
{
get
{
if( this.UpdateStartDate.HasValue )
return this.UpdateStartDate.Value.ToUniversalTime().ToString( "s", CultureInfo.InvariantCulture );
else
return null;
}
set
{
// should implement this...
}
}
// this property is not transformed to JSon. Basically hidden
public DateTime? UpdateStartDate { get; set; }
[DataMember]
public ExportStatus Status { get; set; }
}
The class above defines two methods to handle the UpdateStartDate. One that contains the nullable DateTime property, and the other convert the DateTime? to a string for the JSon response from my service.

Why not just pass it as an already formatted string?
That is, don't pass the date in your DataContract as a date. Make that member a string instead, and format the string the way your client it wants it.

Related

ASP.NET MVC controller losing a day on conversion

I'm sending some data from a local application to another one (ASP.NET MVC). The data is an array of DTOs. I am testing this on my local machine.
The local application is a Web Forms and is sending the data using a service. I do not use JsonResult.
The serialzed DTO is sent correctly, but the dates are deserialized incorrectly on the MVC side, being a day behind then the ones sent.
The DTO class looks like this:
[DataContract]
public class ProjectInfoDto
{
[DataMember]
public long ProjectId { get; set; }
[DataMember]
public string ProjcetCode { get; set; }
[DataMember]
public DateTime BeginDate { get; set; }
[DataMember]
public DateTime FinalDate { get; set; }
}
I am serializing the data using the below method:
public static string JsonSerialize<T>(T obj)
{
var serializer = new DataContractJsonSerializer(obj.GetType());
var ms = new MemoryStream();
serializer.WriteObject(ms, obj);
string retVal = Encoding.Default.GetString(ms.ToArray());
ms.Dispose();
return retVal;
}
The JSON sent to the MVC application looks like this (with correct dates):
{"ProjectId":"222","ProjcetCode":"OP9089","BeginDate":"/Date(1461790800000+0300)/","FinalDate":"/Date(1557435600000+0300)/" }
The method receiving the data looks like this:
public ActionResult GetProjectData(ProjectInfoDto[] info) {...}
The original dates are (from the database):
BeginDate -> 2016-04-28 00:00:00.000
FinalDate -> 2019-05-10 00:00:00.000
The dates on the MVC side when looking at the received array:
BeginDate -> 2016-04-27 00:00:00.000
FinalDate -> 2019-05-09 00:00:00.000
I don't know why the dates are a day behind when received.
I found a suggestion in this question Is there a way to override how DataContractJsonSerializer serializes Dates?.
The answer in the question suggests creating an instance method and decorate it using the [OnSerializing] attribute. This will allow custom serialization for certain attributes.
Full code below:
[DataContract]
public class ProjectInfoDto
{
[DataMember(Name = "BeginDate")]
private string beginDate;
[DataMember(Name = "ExecutieDataFinal")]
private string finalDate;
[DataMember]
public long ProjectId { get; set; }
[DataMember]
public string ProjcetCode { get; set; }
public DateTime BeginDate { get; set; }
public DateTime FinalDate { get; set; }
[OnSerializing]
void OnSerializing(StreamingContext context)
{
beginDate = BeginDate.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture);
finalDate = FinalDate.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture);
}
}
The idea is to leave the DateTime properties intact, and use the private string fields for the serialzation. In the OnSerializing method, you convert the DateTime properties to the required format. As per the suggestions in the comments to my question, I used the ISO-8601 format ("yyyy-MM-dd").

Unity3D, creating a Json post request

I have to create a post request in Json in this format.
{
"request": {
"application": "APPLICATION_CODE",
"auth": "API_ACCESS_TOKEN",
"notifications": [{
"send_date": "now", // YYYY-MM-DD HH:mm OR 'now'
"ignore_user_timezone": true, // or false
"content": "Hello world!"
}]
}
}
This is my first time serializing Json String and I have no idea how to do this, I have tried a few different things but could never get the exact format.
Would really appreciate any kind of help.
Thanks!
First, you cannot put comment on a json file, but I guess it was just there for now.
Then you can paste your json in converters like this one http://json2csharp.com/
And you get the following:
public class Notification
{
public string send_date { get; set; }
public bool ignore_user_timezone { get; set; }
public string content { get; set; }
}
public class Request
{
public string application { get; set; }
public string auth { get; set; }
public List<Notification> notifications { get; set; }
}
public class RootObject
{
public Request request { get; set; }
}
Now you need to fix a few issues that are required for JsonUtility:
[Serializable]
public class Notification
{
public string send_date;
public bool ignore_user_timezone;
public string content;
}
[Serializable]
public class Request
{
public string application;
public string auth;
public List<Notification> notifications;
}
[Serializable]
public class RootObject
{
public Request request;
}
Finally:
RootObject root = JsonUtility.FromJson<RootObject>(jsonStringFile);
You can also use SimpleJSON like this ;
string GetRequest () {
JSONNode root = JSONNode.Parse("{}");
JSONNode request = root ["request"].AsObject;
request["application"] = "APPLICATION_CODE";
request["auth"] = "API_ACCESS_TOKEN";
JSONNode notification = request ["notifications"].AsArray;
notification[0]["send_date"] = DateTime.Now.ToString("yyyy-MM-dd HH:mm");
notification[0]["ignore_user_timezone"] = "true";
notification[0]["content"] = "Hello world!";
return root.ToString ();
}

.net Web API Json Property attribute not working when serilize using JsonConvert.serilizeObject

Json libarary to convert data to json
this is my main method which return two list one with property list
List and another is List
public static Tuple<List<RoomDayBook>, List<string>> DayBookRowData(DateTime StartDate, DateTime EndDate, int SupplierId, bool wantSubRoom)
{
DataSet dsDayBook = FillDayBookData(StartDate, EndDate, SupplierId);
............................
............................
lstDayBook.Add(objDayBook);
}
return new Tuple<List<RoomDayBook>, List<string>>(lstDayBook, Guests);
}
In this RoomDayBook class in which i use JsonProperty which give jsonproperty name in json serilization in stand of property name
public class RoomDayBook
{
[JsonProperty(PropertyName = "RC")]
public string RoomCode { get; set; }
[JsonProperty(PropertyName = "RN")]
public string RoomName { get; set; }
[JsonProperty(PropertyName = "HS")]
public bool HasSubRoom { get; set; }
[JsonProperty(PropertyName = "RD")]
public List<RoomDetail> RoomDetails { get; set; }
[JsonProperty(PropertyName = "SRs", NullValueHandling = NullValueHandling.Ignore)]
public List<RoomDayBook> SubRooms { get; set; }
}
it's woking perfectly in normal aspx webmethods but not working in web api please help me find me reason behind it
I found problem in different version of Newton.json library different between class library and Web API Project that's it not convert it in proper format

Send JSON date to WCF service

I want to post json object to my WCF service
My only problem is his date property. I get the date from an jquery datepicker and i want to get it in my service as c# datetime.
My service:
namespace Employee
{
[ServiceContract]
public interface IService1
{
[OperationContract]
[WebInvoke(Method = "POST",
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Wrapped)]
bool UpdateEmployee(Employee Employee);
}
}
And this is Employee:
[DataContract]
public class Employee
{
[DataMember]
public string Name { get; set; }
[DataMember]
public string Department { get; set; }
[DataMember]
public int Salary { get; set; }
[DataMember]
public DateTime Hired { get; set; }
}
All the other properties work fine. I just need to convert my date string to json date.
The expected format for DateTime object is not the format returned by jQuery's date picker. WCF expects the date in the ASP.NET format (e.g., \/Date(1234567890)\/).
You can use other formats, though, but it's not simple (at least not until .NET 4.0; on 4.5 this got a lot better). Basically, you'd use a string property (which can be private, if your service is running under full trust) which would get the value from the wire, then hook it up to a DateTime property during the serialization episodes. There's more information about this trick at http://blogs.msdn.com/b/carlosfigueira/archive/2011/09/06/wcf-extensibility-serialization-callbacks.aspx, and you can see it on the code below.
namespace StackOverflow_11105856
{
[ServiceContract]
public interface IService1
{
[OperationContract]
[WebInvoke(Method = "POST",
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Wrapped)]
string UpdateEmployee(Employee Employee);
}
public class Service : IService1
{
public string UpdateEmployee(Employee Employee)
{
return string.Format("Name={0},Hired={1}", Employee.Name, Employee.Hired.ToString("yyyy-MM-dd HH:mm:ss"));
}
}
[DataContract]
public class Employee
{
[DataMember]
public string Name { get; set; }
[DataMember]
public string Department { get; set; }
[DataMember]
public int Salary { get; set; }
public DateTime Hired { get; set; }
[DataMember(Name = "Hired")]
private string HiredForSerialization { get; set; }
[OnSerializing]
void OnSerializing(StreamingContext ctx)
{
this.HiredForSerialization = this.Hired.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture);
}
[OnDeserializing]
void OnDeserializing(StreamingContext ctx)
{
this.HiredForSerialization = "1900-01-01";
}
[OnDeserialized]
void OnDeserialized(StreamingContext ctx)
{
this.Hired = DateTime.ParseExact(this.HiredForSerialization, "MM/dd/yyyy", CultureInfo.InvariantCulture);
}
}
}
And the jQuery call:
function StackOverflow_11105856_Test() {
var url = "/StackOverflow_11105856.svc/UpdateEmployee";
var data = {
Name: "John Doe",
Department: "Accounting",
Salary: 50000,
Hired: $("#StackOverflow_11105856_datepicker").val()
};
$.ajax({
type: 'POST',
url: url,
contentType: "application/json",
data: JSON.stringify({ Employee: data }),
success: function (result) {
$("#result").text(result.UpdateEmployeeResult);
}
});
}
You should try changing the property BodyStyle = WebMessageBodyStyle.Wrapped to BodyStyle = WebMessageBodyStyle.Bare. This way the framework won't add any extra XML decorations.
Also, you should check the date format coming from the client.
Perhaps you should send it from the client in a pre-set format and then have a string property in your object, rather than a DateTime one.
You can add a read-only property which converts the date string to a DateTime, using the already known format.

Deserialize JSON in Silverlight 4

I have a class MyItems in my namespace as
[DataContract]
public class MyItems {
[DataMember]
public int LineNum { get; set; }
[DataMember]
public string ItemCode { get; set; }
[DataMember]
public string Priority { get; set; }
[DataMember]
public string Contact { get; set; }
[DataMember]
public string Message { get; set; }
}
and on an XAML I have a button and in its action listener, I am trying to deserialize the JSON string that is coming from a form and trying to update a DataGrid.
In the first step Inside the action listener, I am trying..
List<MyItems> myItems= JSONHelper.DeserializeToMyItems<myItems>(result);
and result (of type string ) has
{"MyItems":[{"LineNum":"1","ItemCode":"A00001","Contact":"5","Priority":"1","Message":"IBM Infoprint 1312"}, {"LineNum":"2","ItemCode":"A00002","Contact":"5","Priority":"1","Message":"IBM Infoprint 1222"}, {"LineNum":"3","ItemCode":"A00003","Contact":"5","Priority":"1","Message":"IBM Infoprint 1226"}, {"LineNum":"4","ItemCode":"A00004","Contact":"5","Priority":"1","Message":"HP Color Laser Jet 5"}, {"LineNum":"5","ItemCode":"A00005","Contact":"5","Priority":"1","Message":"HP Color Laser Jet 4"}]}
The JSONHelper.DeserializeToMyItems code looks like,
public static List<MyItems> DeserializeToMyItems<MyItems>(string jsonString) { MyItems data = Activator.CreateInstance<MyItems>(); using (MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(jsonString))) { DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(List<MyItems>)); return (List<MyItems>)serializer.ReadObject(ms); } }
While running, I get an exception at the line serializer.ReadObject(ms)
Unable to cast object of type 'System.Object' to type 'System.Collections.Generic.List`1[ServiceTicket.MyItems]'.
I am not sure how to do a type cast for and I am handling a List of type MyItems. Can anyone help me on this please ?. would be highly appreciated as I am new on Silverlight.
thanks
Denny
Try following, it should resolve your problem.
public class JsonHelper
{
public static T Deserialize<T>(string json)
{
using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(json)))
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
return (T)serializer.ReadObject(ms);
}
}
}
and use the above method like following:
List<MyItems> myItems = JsonHelper.Deserialize<List<MyItems>>(result);
Hope this helps!