内容' \ /日期('')\ /'不以' \ /日期开头('以'结尾)\ /'根据JSON的要求

时间:2017-05-28 13:06:32

标签: c# json web-services wcf

我想向WCF休息服务发送帖子请求,如您所见:

Guid id;
id = Guid.NewGuid();

var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://localhost:47026/NewsRepository.svc/AddNews");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
    string json = new JavaScriptSerializer().Serialize(new
    {       
        id = id,
        Subject="wfwf",
        ViewerCounter="1",
        Content="fsdsd",
        SubmitDatatime="2012/12/12",
        ModifiedDateTime="2012/12/12",
        PublisherName="sdaadasd",
        PictureAddress="adfafsd",
        TypeOfNews="adsadaad"                       
    });

    streamWriter.Write(json);
}
try 
{ 
    var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
    using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
    {
        var result = streamReader.ReadToEnd();
    }
}
catch(Exception er)
{
    MessageBox.Show(er.ToString());
}

但我得到一个错误 - 400个错误请求。所以我跟踪了我的WCF日志文件,发现了这个错误:

  

反序列化CMSManagement.Domain.Entity.News类型的对象时出错。 DateTime内容' 2012/12/12'不以' /日期开头('并以'结尾)/'根据JSON的要求。

在亲爱的朋友@svek代码之后。结果是这样的:

Guid id;
id = Guid.NewGuid();

var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://localhost:47026/NewsRepository.svc/AddNews");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "PUT";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
    JsonSerializerSettings microsoftDateFormatSettings = new JsonSerializerSettings
    {
        DateFormatHandling = DateFormatHandling.MicrosoftDateFormat
    };

    string json = JsonConvert.SerializeObject(new
    {
        id = id,
        Subject = "wfwf",
        ViewerCounter = "1",
        Content = "fsdsd",
        SubmitDatatime = "2012/12/12",
        ModifiedDateTime = "2012/12/12",
        PublisherName = "sdaadasd",
        PictureAddress = "adfafsd",
        TypeOfNews = "adsadaad"
    }, microsoftDateFormatSettings);
    streamWriter.Write(json);
}
try 
{ 
    var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
    using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
    {
        var result = streamReader.ReadToEnd();
    }
}
catch(Exception er)
{
    MessageBox.Show(er.ToString());
}

但我得到同样的错误。为什么呢?

1 个答案:

答案 0 :(得分:10)

使用JsonConvert

而不是使用

string json = new JavaScriptSerializer().Serialize( new {...} );

使用

//using Newtonsoft.Json;
string json = JsonConvert.SerializeObject(new {...} );

设置DateTime格式

  

在Json.NET 4.5之前,使用Microsoft格式编写日期:“/ Date(1198908717056)/”。如果要使用此格式,或者希望保持与Microsoft JSON序列化程序或旧版本Json.NET的兼容性,请将DateFormatHandling设置更改为MicrosoftDateFormat。

来源:http://www.newtonsoft.com/json/help/html/DatesInJSON.htm

默认Json.NET 4.5格式

// default as of Json.NET 4.5
string isoJson = JsonConvert.SerializeObject(data);
// { "MyDateProperty":"2009-02-15T00:00:00Z" }
  

Microsoft日期格式

JsonSerializerSettings microsoftDateFormatSettings = new JsonSerializerSettings
{
    DateFormatHandling = DateFormatHandling.MicrosoftDateFormat
};

string microsoftJson = JsonConvert.SerializeObject(data, microsoftDateFormatSettings);
// { "MyDateProperty":"\/Date(1234656000000)\/" }

JavaScript JSON格式

string javascriptJson = JsonConvert.SerializeObject(data, 
    new JavaScriptDateTimeConverter());
// { "MyDateProperty":new Date(1234656000000)}

解决方案代码

以下是您问题的完整解决方案:

JsonSerializerSettings microsoftDateFormatSettings = new JsonSerializerSettings
{
    DateFormatHandling = DateFormatHandling.MicrosoftDateFormat
};

string json = JsonConvert.SerializeObject(new
{
    id = id,
    Subject = "wfwf",
    ViewerCounter = "1",
    Content = "fsdsd",
    SubmitDatatime = "2012/12/12",
    ModifiedDateTime = "2012/12/12",
    PublisherName = "sdaadasd",
    PictureAddress = "adfafsd",
    TypeOfNews = "adsadaad"

}, microsoftDateFormatSettings); // ⇦ Added the format argument here

using (StreamWriter streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
    JsonSerializer serializer = new JsonSerializer();
    serializer.Serialize(streamWriter, json);
}