c#
  • json
  • json.net
  • 2014-10-11 28 views 2 likes 
    2

    我用KnockoutJS viewmodel創建了一個頁面。我想使用Web API將數據發佈到我的服務器。JsonConvert.DeserializeObject <T>(值)不反序列化分配的對象

    我使用AJAX後:

    $.ajax({ 
          url: "/api/blogpost", 
          contenttype: "application/x-www-form-urlencoded", 
          data: '=' + encodeURIComponent(ko.toJSON(self.Blog)), 
          type: "POST", 
          dataType: "JSON", 
          timeout: 10000, 
          success: function (Result) { 
    
          }, 
          error: function (xhr, status) { 
           alert(status + " - " + xhr.responseText); 
          } 
         }); 
    

    將JSON數據發送到我的Web API方法。 這是發送到服務器的JSON:

    { 
    "BlogTitle": "Sample Post", 
    "BlogHTML": "<p><strong>Sample JSON Blog Post</strong></p>\n\n<h1><strong>It never works :(&nbsp;</strong></h1>\n", 
    "BlogThumbnail": "http://mysystemURL/SamplePost/What.jpg", 
    "BlogSummary": "This is a sample post", 
    "BlogFQURL": "Sample_Post", 
    "BlogTags": [ 
        "json", 
        "devlopment", 
        "newtag", 
        "" 
    ], 
    "BlogCategory": 1 
    } 
    

    我的Web API方法正確接收JSON數據。原始的字符串值,如下所示:

    "{\"BlogTitle\":\"Sample Post\",\"BlogHTML\":\"<p><strong>Sample JSON Blog Post</strong></p>\\n\\n<h1><strong>It never Works :(</strong></h1>\\n\",\"BlogThumbnail\":\"http://mysystemURL/SamplePost/What.jpg\",\"BlogSummary\":\"This is a sample post\",\"BlogFQURL\":\"Sample_Post\",\"BlogTags\":\"[\\\"json\\\",\\\"devlopment\\\",\\\"newtag\\\",\\\"\\\"]\",\"BlogCategory\":1}" 
    

    當我使用JSON visulizer我的數據,我得到這樣的: Using the VS Built In Visualiser

    我用這個BlogPost vari = JsonConvert.DeserializeObject<BlogPost>(value);進行反序列化我的對象,但一切都保持

    Debugging my vari object

    我的博文對象看起來是這樣的:

    public class BlogPost 
    { 
        public int BlogPostID { get; set; } 
        public string BlogPostTitle { get; set; } 
        public string BlogPostHTML { get; set; } 
        public string BlogPostThumbnailURL { get; set; } 
        public string BlogPostSummary { get; set; } 
        public string BlogPostFQURL { get; set; } 
        public int BlogPostCategory { get; set; } 
        public List<TagDTO> BlogPostTags { get; set; } 
    } 
    

    我真的很難倒..任何幫助將不勝感激!

    回答

    6

    您的房產名稱不符。 C#對象的屬性是BlogPost*,JSON有Blog*,沒有

    更正Javascript或C#端的名稱或使用JsonProperty屬性指定序列化屬性的名稱。

    +0

    您好!是一位學者和先生們 – 2014-10-11 22:15:37

    相關問題