在web api的action方法中,Json数据没有正确序列化

时间:2015-06-10 05:31:49

标签: c# json asp.net-mvc asp.net-web-api

我试图将以下数据发布到我的json格式的action方法中,并尝试接受JSon数据以自动序列化到我的类型类,但它没有发生。可以告诉我哪里出错了?

标题:

User-Agent: Fiddler
Host: localhost:62813
Content-Length: 103
contentType: 'application/json; charset=utf-8'

Web API中的操作方法:

 public void Post([FromBody]Book value)
 {

 }

输入Json数据:

{
"Title": "asasd",
"Author": "asaa",
"Publisher": "Asaas",
"Category": "asdasd",
"Price": "12"
}

型号:

public class Book : Product
    {
        [Required(ErrorMessage="Title is required")]
        public string Title { get; set; }
        [Required(ErrorMessage = "Author is required")]
        public string Author { get; set; }
        [Required(ErrorMessage = "Publisher is required")]
        public string Publisher { get; set; }
        [Required(ErrorMessage = "Category is required")]
        public string Category { get; set; }        
        [Range(1, 1000)]
        public override decimal Price
        {
            get;
            set;

        }


    }

我希望这些数据作为参数出现在我的动作方法中,但我总是得到 null

2 个答案:

答案 0 :(得分:1)

我重新创建了代码,这是我的解决方案 -

标题 - (您的 do script "instruments -w " & device_id & " -t /Applications/Xcode.app/Contents/Applications/Instruments.app/Contents/PlugIns/AutomationInstrument.xrplugin/Contents/Resources/Automation.tracetemplate " & bundle_name & " -e UIASCRIPT " & script_path & " -e UIARESULTSPATH " & trace_output & ";" in newWin 存在问题)

DB > design docs > ddoc > remove view code > save ddoc

请求正文 -

content-type

以下是完整提琴手请求的截图 -

enter image description here

然后我能够在我的行动中获得User-Agent: Fiddler Host: localhost:1655 Content-Length: 103 Content-Type: application/json; charset=utf-8 -

enter image description here

其他信息请查看我的以下路线 -

{
"Title": "asasd",
"Author": "asaa",
"Publisher": "Asaas",
"Category": "asdasd",
"Price": "12"
}

答案 1 :(得分:0)

您可以使用DataContractJsonSerializer

[DataContract]
public class Book : Product
{
    [DataMember]
    [Required(ErrorMessage="Title is required")]
    public string Title { get; set; }
    [DataMember]
    [Required(ErrorMessage = "Author is required")]
    public string Author { get; set; }
    [DataMember]
    [Required(ErrorMessage = "Publisher is required")]
    public string Publisher { get; set; }
    [DataMember]
    [Required(ErrorMessage = "Category is required")]
    public string Category { get; set; }  
    [DataMember]      
    [Range(1, 1000)]
    public override decimal Price { get; set; }
}

然后在你的控制器中

var ser = new DataContractJsonSerializer(typeof(Book));
using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(jsonData))
{
    Book book = ser.ReadObject(ms) as Book;
}

这样的事情应该这样做。在DataContractJsonSeriailzer上阅读一下。