日期和JSON.stringify() [英] Date and JSON.stringify()
问题描述
我编写了一个使用jquery以JSON格式对对象进行字符串化的代码。
var o = new Object();
o.Price = 56;
o.Reason = Tea;
var followupDate = 17-12- 2013\" 跨度>;
o。日期 = 新 日期跨度>(followupDate);
var str = JSON .stringify(o);
这里'str'是我得到一个json的字符串。
{ Price: 56, 原因 : Tea, 日期: 2013-12-17T06:33:18.058Z }
当我将此字符串传递给我的wcf方法时,我收到错误
反序列化WcfService1.ExpenseClass类型的对象时出错。 DateTime内容'2013-12-17T06:33:18.058Z'不以'/ Date('和以')/'开头,如JSON所示。
这是我用来将json字符串转换为类的代码
ExpenseClass exp = < span class =code-keyword> new ExpenseClass();
使用(MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(str)))
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer( typeof (ExpenseClass));
exp = serializer.ReadObject(ms) as ExpenseClass; // 此处遇到错误
}
我该怎么办?
试试这个.. :)
JsonConvert.SerializeObject( this ,Formatting.None, new IsoDateTimeConverter(){DateTimeFormat = yyyy-MM-dd hh:mm:ss}) ;
Alsalaam Aleykum。
所有你需要做的就是回应错误。我的意思是更改日期格式,以便json可以将其解析为Web服务。
您的代码应该如下所示:
var o = new Object();
o.Price = 56;
o.Reason = Tea;
var followupDate = 17-12- 2013\" 跨度>;
o。日期 = 新 日期跨度>(followupDate);
o。日期 = \ /日期( + o。日期 .valueOf()+ )\ /跨度>;
// valueOf()方法返回Date对象的原始值。
I have written a code to stringify an object in JSON format using jquery.
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.
{"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
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?
try this..:)
JsonConvert.SerializeObject(this, Formatting.None, new IsoDateTimeConverter() { DateTimeFormat = "yyyy-MM-dd hh:mm:ss" });
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:
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.
这篇关于日期和JSON.stringify()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!