开发者

WCF - Rest and JSON Operation Parameters

开发者 https://www.devze.com 2022-12-10 22:30 出处:网络
I\'m implementing a generic restful api in WCF. I require access to a generic object deserialized from JSON (as a parameter to a POST operation). I\'m using the raw programming model to permit fine-gr

I'm implementing a generic restful api in WCF. I require access to a generic object deserialized from JSON (as a parameter to a POST operation). I'm using the raw programming model to permit fine-grained control of the return format. For example:

// Create
[OperationContract(Name = "CreateJSON")]
[WebInvoke(UriTemplate = "{endpointName}", Method = "POST", BodyStyle = WebMessageBodyStyle.Bare, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
Stream Create(Object input, String endpointName);

In the above example the generic object is given by the parameter 'input' that I expect to be the POST payload. An 开发者_JS百科analogous call works fine with an endpoint targeted for xml, but not JSON.

Any ideas/assistance would be greatly appreciated. Anyone?


There is a namespace System.Runtime.Serialization.Json

To serialize generic object you can do like this:

/// Object to Json
let internal json<'t> (myObj:'t) =  
        use ms = new MemoryStream()
        (new DataContractJsonSerializer(typeof<'t>)).WriteObject(ms, myObj)
        Encoding.Default.GetString(ms.ToArray())

...

/// Object from Json
let internal unjson<'t> (jsonString:string)  : 't = 
        use ms = new MemoryStream(ASCIIEncoding.Default.GetBytes(jsonString))
        let obj = (new DataContractJsonSerializer(typeof<'t>)).ReadObject(ms)
        obj :?> 't

I hope that F# is ok... ;-)

0

精彩评论

暂无评论...
验证码 换一张
取 消