【问题标题】:NancyFX : Deserialize JSONNancyFX:反序列化 JSON
【发布时间】:2012-05-23 15:22:32
【问题描述】:

文档建议 NancyFx 帮助我完成 json 请求正文的 WRT 反序列化,但我不确定如何。请参阅下面的测试来演示:

[TestFixture]
public class ScratchNancy
{
    [Test]
    public void RootTest()
    {
        var result = new Browser(new DefaultNancyBootstrapper()).Post(
            "/",
            with =>
                {
                    with.HttpRequest();
                    with.JsonBody(JsonConvert.SerializeObject(new DTO {Name = "Dto", Value = 9}));
                });

        Assert.AreEqual(HttpStatusCode.OK, result.StatusCode);
    }

    public class RootModule : NancyModule
    {
        public RootModule()
        {
            Post["/"] = Root;
        }

        private Response Root(dynamic o)
        {
            DTO dto = null;//how do I get the dto from the body of the request without reading the stream and deserializing myself?

            return HttpStatusCode.OK;
        }
    }

    public class DTO
    {
        public string Name { get; set; }
        public int Value { get; set; }
    }
}

【问题讨论】:

    标签: .net json rest nancy


    【解决方案1】:

    Model-binding

    var f = this.Bind<Foo>();
    

    编辑(为了这个问题的其他读者的利益,把上面放在上下文中)

    public class RootModule : NancyModule
    {
        public RootModule()
        {
            Post["/"] = Root;
        }
    
        private Response Root(dynamic o)
        {
            DTO dto = this.Bind<DTO>(); //Bind is an extension method defined in Nancy.ModelBinding
    
            return HttpStatusCode.OK;
        }
    }
    

    【讨论】:

    • 知道了,谢谢,简洁优雅。我爱上了南希。
    • o被序列化有什么先决条件吗?我传递了一个有效的 JSON 字符串,但我的动态对象没有键或值。
    猜你喜欢
    • 1970-01-01
    • 2013-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多