Content '\/Date('')\/' does not start with '\/Date(' and end with ')\/' as required for JSON

前端 未结 1 1307
长情又很酷
长情又很酷 2021-01-02 16:11

I want to send a post request to a WCF rest service as you can see:

Guid id;
id = Guid.NewGuid();

var httpWebRequest = (HttpWebRequest)WebRequest.Create(\"h         


        
相关标签:
1条回答
  • 2021-01-02 16:54

    Use JsonConvert

    Instead of using the

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

    use

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

    Setting up the DateTime format

    Prior to Json.NET 4.5 dates were written using the Microsoft format: "/Date(1198908717056)/". If you want to use this format, or you want to maintain compatibility with Microsoft JSON serializers or older versions of Json.NET, then change the DateFormatHandling setting to MicrosoftDateFormat.

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

    Default Json.NET 4.5 Format

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

    Microsoft Date Format

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

    JavaScript JSON Format

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

    Solution Code

    Here is the full working solution for your question:

    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);
    }
    
    0 讨论(0)
提交回复
热议问题