ServiceStack and dynamic properties in DTO requests

I would like to place a JSON object in a service stack service and use a dynamic property in a DTO request. All the approaches I've tried so far leave the object NULL.

The javascript code I'm using is:

$.getJSON( "/api/json/reply/Hello", { Name: "Murphy", Laws: { SomeProp: "A list of my laws", SomeArr: [ { Title: "First law" }, { Title: "Second law" }, { Title: "Third law" } ] } }, function(data) { alert(data.result); } ); 

DTO will receive a request:

 public class Hello { public string Name { get; set; } public dynamic Laws { get; set; } } 

I also tried using object and JsonObject instead of dynamic in DTO.

To be complete, here is also a service:

 public class HelloService : Service { public object Any(Hello request) { return new HelloResponse { Result = "Hello, " + request.Name }; } } 

Murphy infiltrates the Name property without any problems, but the Laws property remains NULL.

In the end, I want to somehow iterate (using reflection?) Over the Laws property and get all the contained properties and values.

I can’t use a typed DTO here because I don’t know the JSON properties of Laws at design time (and it can change quite often).

Thanks for any help!

+4
source share
1 answer

.NET 3.5 libraries created in ServiceStack on NuGet do not have native support like .NET . You can pass JSON to the string property and dynamically parse it on the server:

 public object Any(Hello request) { var laws = JsonObject.Parse(request.Laws); laws["SomeProp"] // laws.ArrayObjects("SomeArr") // } 

Otherwise, you can use Dictionary<string,string> or specify in AppHost:

 JsConfig.ConvertObjectTypesIntoStringDictionary = true; 

You can use an object that will process objects such as a string dictionary.

Otherwise, the dynamics should not be on the DTO, because it does not make sense with respect to the expected service. You can simply add it to a QueryString. You can use JSV Format to specify complex graphs of objects in a QueryString, for example:

 /hello?laws={SomeProp:A list of my laws,SomeArr:[{Title:First Law}]} 

Note: spaces above are encoded with %20 on the wire.

Access to your services with:

 public object Any(Hello request) { var laws = base.QueryString["laws"].FromJsv<SomeTypeMatchingJsvSent>(); } 
+5
source

All Articles