views:

208

answers:

4

I have a WCF REST service built with C# and it returns an image as part of a CPU intensive operation. The client is running on Android (Java) By default, it will return a text JSON object that looks something like this:

{"d",[9,0,77,12,11,...]}

Those are they bytes of the image. Fine. However, all the solutions for decoding this JSON are intolerably slow. I've tried Gson, Jackson, and the built-in Android JSONObject class. I have no idea why they are so slow.

As an alternative solution, I have my REST service return a GUID, and then that GUID can be used by the Android client to go to a regular URL that serves up the image as a regular binary stream, via an MVC controller.

This works well, and it fast, and is pretty easy to handle on the Android side. However, it does feel like a bit of kludge and kind of a violation of the REST design principles.

Am I missing something here? Is there a better way to do this?

+2  A: 

How about your REST service return a Redirect 303 with a Location header that has an URL that points to the image? Or why not just return the bytes directly from the first URL?

As far as RESTful or not, returning a JSON encoded image is not exactly in the spirit of the REST self-descriptive constraint.

Just make sure the endpoint that returns the image stream of bytes, actually uses an image/* media type in the content header.

Darrel Miller
Using WCF, you are restricted to returning JSON or XML
Alex Kilpatrick
No, that is not true. I have a WCF service that I return a dozen different media types from. Use Stream as your method return type and you can return anything.
Darrel Miller
Hmm. I was looking at: [WebGet(ResponseFormat = WebMessageFormat.Xml)]That only gives you XML or Json.However, if you use:WebOperationContext.Current.OutgoingResponse.ContentType = "text/xml"It looks like you can return any type. Thanks!
Alex Kilpatrick
A: 

Well, on of your main problems is trying to transmit binary data using a text format. Most if not all java json libraries will try to recognize the type of the field. It'll take a long time if there's a lot of fields.

Yeah, streaming it directly is a lot faster. Maybe you can use XML since it supports binary or blob data.

Miguel Morales
A: 

As Darrel wrote above, if the URL computes and returns an Image, simply return that Image with an appropriate content-type, for e.g., as a PNG image. Transmitting the image encoded within JSON is a strange choice, to say the least.

Rajeev J Sebastian
A: 

There is a great talk about developing rest client application on android form Google IO 2010.

http://www.youtube.com/watch?v=xHXn3Kg2IQE

This session will present architectural considerations for developing RESTful applications on the Android platform. It focuses on design patterns, platform integration and performance issues specific to the Android platform.

A great resource and must watch.

nick