2012-05-23 13 views
7

Dokumentacja sugeruje, że NancyFx pomaga mi w deserializacji WRT treści żądania json, ale nie jestem pewien jak. Zobacz testy poniżej wykazać: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; } 
    } 
} 

Odpowiedz

15

Model-binding

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

EDIT (umieścić powyżej w kontekście z korzyścią dla innych czytelników o tym mowa)

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

got it, dzięki prostym i elegancki. Zakochuję się w Nancy. –

+0

Czy jest jakiś warunek wstępny do serializacji? Przekazuję prawidłowy ciąg JSON, ale mój obiekt dynamiczny nie ma kluczy ani wartości. –

Powiązane problemy