.net - 南希FX : Deserialize JSON

标签 .net json rest nancy

文档建议 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; }
    }
}

最佳答案

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;
    }
}

关于.net - 南希FX : Deserialize JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10723044/

相关文章:

c# - DbDataRecord - entry.CurrentValues 和 entry.originalValues 相同

c# - WinProcEvent 一个或多个 SetWinEventHook 回调?

php - 添加将在 PHP 中以 JSON 编码的 mysql 查询结果的值?

javascript - AngularJS Json 列表

python - Django 从 JSON 数据创建一个 QueryDict

php - CodeIgniter REST API 库 Ajax PUT 抛出 403 禁止

c# - 无法验证用户名和密码

c# - C# 在同一个套接字上发送+接收数据

javascript - 如何访问json返回的对象的对象

java - Eclipse 上的 tomcat 服务器 : how to make tomcat server reload project context at will