Monday, May 14, 2012

Retrieve Json from service and pass to ApiController

I want to directly capture JSON from an external API in a service layer, return that to a MVC 4 ApiController, and then output the JSON through that ApiController. I'm basically writing a wrapper around another API service because some other actions have to happen at the same time (authentication, etc). The problem is that the JSON gets converted to a string and is passed around as a string in my C# code. This just adds escape characters to the JSON. Is there anyway I can just pass the JSON object around in my C# code? Details of my implementation are below.



In a service layer, I'm consuming an API that provides JSON via the method below.



return new WebClient().DownloadString(url);


Unfortunately this returns a string. As this API is already returning JSON to me this is problematic because lots of escape characters get added to the string.



The JSON should look something like this



[{"Citation":{"Attachments":[{"AttachedPersonIds":null,..."Type":"Record"}]


But instead it now looks like this



"[{\"Citation\":{\"Attachments\":[{\"AttachedPersonIds\":null,...\"Type\":\"Record\"}]"


After I get this string I return it through a couple of methods to an ApiController (which is setup to return JSON) like this.



public class HintsController : ApiController
{
public string Get(string treeId, string personId)
{
return _hintService.GetHints(treeId, personId);
}
}


I've tried to convert the string to a Literal string and tried serializing the string again. Doing this just adds more escape characters and doesn't solve the problem. I think the problem is with how I'm consuming the initial call because it's casting it from JSON to a string. But I don't know how to avoid this.



Thanks in advance for any ideas.





No comments:

Post a Comment