Skip to main content

Return JSON straight up (not a string) in ApiController

The Problem:

Had a hard time returning a plain JSON object from an ApiController (MVC4).  Instead, I'm getting the JSON object as a string. For example:

"{\"dobSP\":\"90.25\",\"latestSP\":\"2025.9\",\"dobStampPrice\":\"0.15\",\"latestStampPrice\":\"0.49\",\"dobStampImage\":\"http://media1.s-nbcnews.com/j/msnbc/Components/Photos/051207/051207_stamp_news_hmed.grid-4x2.jpg\",\"latestStampImage\":\"http://media1.s-nbcnews.com/j/msnbc/Components/Photos/051207/051207_stamp_news_hmed.grid-4x2.jpg\",\"dataUpdated\":\"1/8/2015 11:27:48 AM\"}"

What I've Learned:

My Get method (in the controller) was specified to return a string object.  What I needed to return was a HttpResponseMessage type.  

The Fix:

I simply created a method that created the response for me:

        private HttpResponseMessage ConvertToHttpResponse(string text)
        {
            var response = Request.CreateResponse(HttpStatusCode.OK);
            response.Content = new StringContent(text, Encoding.UTF8, "application/json");
            return response;        
        }

When returning the value from my Get method, I simply added this (using JSON.net to serialize):

        return ConvertToHttpResponse(JsonConvert.SerializeObject(payload));


And, here's the result I wanted:

{"dobSP":"90.25","latestSP":"2025.9","dobStampPrice":"0.15","latestStampPrice":"0.49","dobStampImage":"http://media1.s-nbcnews.com/j/msnbc/Components/Photos/051207/051207_stamp_news_hmed.grid-4x2.jpg","latestStampImage":"http://media1.s-nbcnews.com/j/msnbc/Components/Photos/051207/051207_stamp_news_hmed.grid-4x2.jpg","dataUpdated":"1/8/2015 11:27:48 AM"}

Hope this helps somebody

More Reading:

http://stackoverflow.com/questions/23227952/apicontroller-to-return-json-string-as-is
http://msdn.microsoft.com/en-us/library/system.net.http.httpresponsemessage%28v=vs.118%29.aspx


Comments

Popular posts from this blog

Resolved Sitecore "If you publish now, the selected version will not be visible on the web site" warning

The Problem:   Unable to publish any Sitecore item within a particular site, even out of the workflow. Rather, a warning reads " If you publish now, the selected version will not be visible on the web site " What I've Discovered: I couldn't publish any item in the site, not just one or two I viewed all parent items of the items in question The main home page displayed a different warning " This item will never be published because it's publishable option is disabled " Another sitecore developer reminded me of the standard fields option View --> check standard fields to show all standard page fields Found out that somebody checked Never Publish within the publishing section The Fix: After I unchecked the checkbox and saved the change, I was able to publish again.  :) Conclusion: Looks like another Sitecore user thought the children items would not be affected by this change.  Lesson  learned.

[Resolved] Sitecore ParseException: End of string expected at position...

Problem:  I have a line of code that uses Sitecore Fast Query to pull all items + children starting with a site item, like so: Item [] allItems = db.SelectItems( "fast:" + sitecorePath + "//*" ); Unfortunately, I would get a Sitecore parsing error at runtime: ParseException: End of string expected at position... Turns out Sitecore doesn't like hyphens ('-') in any sitecore path when using fast query, which I have a few distributor sites in a folder which contained hyphens. Solution: I create a simple method that resolves a sitecore path to be Sitecore fast query friendly:             string sitecorePath = "" ;             if (siteItem.Paths.FullPath.Contains( "-" ))             {                 String [...

Basic Recursion Example in JavaScript

Problem :  I've been having to write solutions which required some sort of recursion.  The last recursion assignment I had to write was a homework assignment about 10 years ago. I remembered the concept, but forgot how to write it. Solution :  Here’s a simple example of recursion. I start with an array, and after I fire the function, I remove that index from the array, so it shrinks. Once the array is empty, recursion stops.  Pretty straight forward! Code : let books = [ 'Chosen by God', 'Holiness of God', 'Essential Truths', 'Justified by Faith' ]; function readBooks(b){ while (b.length > 0){ console.log('I\'v read ' + b[0]); b.shift(); readBooks(b); } } readBooks(books);