Todilo
Todilo

Reputation: 1334

Deserializing JSON in WCF

I am sending a JSON message including filename, and a base64encoded image to a WCF service. I am not really sure on how to convert it back to the image, more specificallly deserializing the return stream.

WCF Interface

 [OperationContract]
        [WebInvoke(
            Method = "POST",
            UriTemplate = "/UploadImage", ResponseFormat =  WebMessageFormat.Json,
            RequestFormat =  WebMessageFormat.Json)]
        string UploadImage(Stream image);

And some part of the message(which I save to a file so I can view and try to understand)

--hr56lXG6Q_hKg5opmTx4xejr28dU17AC
Content-Disposition: form-data; name="entity"

{"filename":"mypicture.jpg","thebigfile":"\/9j\/4Re6RXhpZgAATU0AKgAAAAgACwEPAAIAAAAOAAAAkgEQAAIAAAAGAAAAoAESAAMAAAABAAYAAAEaAAUAAAABAAAApgEbAAUAAAABAAAArgEoAAMAAAABAAIAAAExAAIAAAATAAAAtgEyAAIAAAAUAAAAygITAAMAAAABAAEAAIdpAAQAAAABAAAA3oglAAQAAAABAAACegAAAoBTb255IEVyaWNzc29uAExUMjZpAAAAAEgAAAABAAAASAAAAAE2LjEuQS4yLjQ1XzUzX2YxMDAApDIwMTI6MTA6MDYgMDk6MzI6MTcAABiCmgAF
        and lots more of the base64 encoded image....
        --hr56lXG6Q_hKg5opmTx4xejr28dU17AC--

How do I deserialize this? Is Stream the way to go? I do not simply want to remove the top rows and then start deserializing the JSON array, I want to know WHY it looks like this.

Upvotes: 2

Views: 1156

Answers (1)

Eugene Osovetsky
Eugene Osovetsky

Reputation: 6541

To process the message you gave, the OperationContract needs to look something like:

[WebInvoke(Method="POST", UriTemplate="/UploadImage", BodyStyle=WebMessageBodyStyle.WrappedRequest, ResponseFormat=WebMessageFormat.Json, RequestFormat=WebMessageFormat.Json)] [OperationContract] string UploadImage(string filename, string thebigfile);

See http://msdn.microsoft.com/en-us/library/bb885100.aspx for more information

You would then need to manually Base64-decode the "thebigfile" parameter using the decoder provided by the .NET Framework. There is no built-in support for Base64 inside JSON as far as I know, see http://msdn.microsoft.com/en-us/library/bb412170.aspx for details on how various data types are supported.

Upvotes: 3

Related Questions