Click here to Skip to main content
15,881,248 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
I have written a code to stringify an object in JSON format using jquery.

JavaScript
var o = new Object();
o.Price = "56";
o.Reason = "Tea";
var followupDate = "17-12-2013";
o.Date = new Date(followupDate);
var str = JSON.stringify(o);


Here the 'str' is the string in which i get a json.

C#
{"Price":"56","Reason":"Tea","Date":"2013-12-17T06:33:18.058Z"}


when i pass this string to my wcf method, i get an error

There was an error deserializing the object of type WcfService1.ExpenseClass. DateTime content '2013-12-17T06:33:18.058Z' does not start with '/Date(' and end with ')/' as required for JSON.

Here is the code which i used to cast json string to a class

C#
ExpenseClass exp = new ExpenseClass();
using (MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(str)))
{
  DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(ExpenseClass));
  exp = serializer.ReadObject(ms) as ExpenseClass; //Error encounters here
}


what shall i do?
Posted

try this..:)

JavaScript
JsonConvert.SerializeObject(this, Formatting.None, new IsoDateTimeConverter() { DateTimeFormat = "yyyy-MM-dd hh:mm:ss" });
 
Share this answer
 
v2
Comments
markand911 17-Dec-13 3:00am    
Where shall i write your code?
Alsalaam Aleykum.

All you have to do is to respond to the error. I mean change the date format so the json can parse it to the web service.

your code should look like this:

JavaScript
var o = new Object();
o.Price = "56";
o.Reason = "Tea";
var followupDate = "17-12-2013";
o.Date = new Date(followupDate);
o.Date = "\/Date("+o.Date.valueOf()+")\/";          
// valueOf() method Returns the primitive value of a Date object.
 
Share this answer
 
Comments
Afzaal Ahmad Zeeshan 8-Sep-15 16:13pm    
First of all this is a very much old question, you should not post answers on old threads just to gain reputation.

Then, why are you setting the value to Date member of o object twice?


o.Date = new Date(followupDate);
o.Date = "\/Date("+o.Date.valueOf()+")\/";
AbubakerIT 10-Sep-15 6:33am    
I just faced this problem recently, and I wanted to share my solution. Anyway, do you have a problem when other members want to gain a reputation. I'm a fresh member and the code project does not recommend members not to add solutions to old threads. Does it?
AbubakerIT 10-Sep-15 6:39am    
BTW, I made it like that just to make it easy to other people and not to use extra variable:

var date = new Date(followupDate);
o.Date = "\/Date("+date.valueOf()+")\/";

Is that what you want?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900