20

We are trying to make mock service to serve JSON. We have plain JSON strings stored in static files and want to serve them to client as they are, without any additional wrappers. E.g. we have json string {"result_code":200,{"name":"John", "lastName": "Doe"}} and we want to get json response on client just like this without any Content or Data wrappers.

We have solution where we use data contracts and deserialize json to C# objects, but that's a bit complicated and we don't need it.

Thank you

1
  • Can you please be more specific what "mock service" is - just some API implementation (like IMyServiceReturningJson in test's process), real server i.e. written with ASP.Net MVC (as Jededuah +1 suggests) or some other technology/language like node.js? Something else altogether? Commented Mar 27, 2014 at 16:08

2 Answers 2

22

You can return a static JSON string by sending the content manually.

public ActionResult Tester()
{
    return Content("{\"result_code\":200,{\"name\":\"John\", \"lastName\": \"Doe\"}}", "application/json");
}

Sorry if that's not exactly what you're asking about

Sign up to request clarification or add additional context in comments.

1 Comment

This serves the result as actual JSON, versus a body with string containing JSON. This is definitely easier to work with on the client side than the accepted answer.
21

You can do this by referencing System.Web.Mvc. Example in a quick console app I threw together:

using System;
using System.Web.Mvc;
using Newtonsoft.Json;

namespace Sandbox
{
    class Program
    {
        private static void Main(string[] args)
        {
            //Added "person" to the JSON so it would deserialize
            var testData = "{\"result_code\":200, \"person\":{\"name\":\"John\", \"lastName\": \"Doe\"}}";

            var result = new JsonResult
            {
                Data = JsonConvert.DeserializeObject(testData)
            };

            Console.WriteLine(result.Data);
            Console.ReadKey();
        }

    }
}

You can just return the JsonResult from the mock method.

1 Comment

Bad advice, this requires de-serializing and re-serializing the object to return.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.