2012-05-23 5 views
7

La documentazione suggerisce che il NancyFx mi aiuta nella deserializzazione WRT del corpo della richiesta json, ma non sono sicuro di come. Vedere prova di seguito per dimostrare: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; } 
    } 
} 

risposta

15

Model-binding

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

EDIT (da mettere sopra in contesto a beneficio di altri lettori di questo argomento)

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

capito, grazie, semplice ed elegante Mi sto innamorando di Nancy. –

+0

Esiste un prerequisito per o essere serializzato? Ho passato una stringa JSON valida ma il mio oggetto dinamico non ha chiavi o valori. –