2012-05-23 3 views
7

NancyFx가 json 요청 본문의 WRT deserialization을 도와 주겠다고 제안했지만 필자는 그 방법을 잘 모릅니다.NancyFX : Deserialize JSON

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

답변

15

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

이있어, 감사, 간단합니다 (이 질문의 다른 독자의 이익을 위해 상황에 위 넣어) : 아래의 테스트를 입증하기 위해 참조 우아한. 나는 낸시와 사랑에 빠지게됩니다. –

+0

o를 직렬화하기위한 전제 조건이 있습니까? 유효한 JSON 문자열을 전달했지만 동적 객체에 키 또는 값이 없습니다. –

관련 문제