3

I'm used to doing this in Django (similar to Ruby on Rails) where in some cases I need to hard code a JSON response object for the client to be able to interpret, but I've been searching everywhere online on figuring out how to do this with ASP.NET web API and I can't find anything on this, ASP.NET web API seems to be forcing me to create a class to represent a JSON response for every URI controller.

For example, here's the only way I know for manually creating a JSON response:

1.) I first need to create the class to represent the response object

public class XYZ_JSON
{
    public string PropertyName { get; set; }
    public string PropertyValue { get; set; }
}

2.) Then I need to properly write up the URI controller that'll return an "XYZ_JSON" that I've just defined above:

// GET: api/ReturnJSON
public XYZ_JSON Get()
{
    XYZ_JSON test = new XYZ_JSON { PropertyName = "Romulus", PropertyValue = "123123" };

    return test;
}

Will result with an http response of something like:

200 OK {"PropertyName":"Romulus", "PropertyValue":"123123"}

This whole class to JSON design pattern is cool and all, but it's not helpful and actually makes things much worse when trying to return a class as a JSON object with many classes within it such as:

public class XYZ_JSON
{
    public string PropertyName { get; set; }
    public string PropertyValue { get; set; }
    public List<ComplexObject> objects { get; set; } // <- do not want
}

The JSON response object above isn't that complex, but for what I'm trying to accomplish I'll have to put a list of classes within a list of classes within a list of classes, and I can't develop it in this awkward way unless I spend a week on it which is just ridiculous.

I need to be able to return a JSON response in this kind of fashion:

// GET: api/ReturnJSON
public JSON_Response Get(string id)
{
    // do some SQL querying here to grab the model or what have you.

    if (somethingGoesWrong = true)
    return {"result":"fail"}
    else
    return {"result":"success","value":"some value goes here"}
}

The design pattern above is what I'm trying to accomplish with ASP.NET web API, a very simply way to return a semi-hard coded JSON response object which would allow me to return very unique and dynamic responses from a single URI. There's going to be many use cases where a list of up to 8 completely unique Class objects will be returned.

Also, If what I'm trying to accomplish is the backwards way of doing things than that's fine. I've released a very successful and stable iOS application with a flawless Django backend server handling things this way perfectly without any issues.

Can someone explain to me how I can return a simple hard coded JSON response using the ASP.NET web API?

Thanks!

Matt Andrzejczuk
  • 2,001
  • 9
  • 36
  • 51

5 Answers5

5

You can create anonymous types in C#, so you can use one of these to produce your hard-coded result. For example:

return new JsonResult
{
    Data = new
    {
        result = "success",
        value = "some value"
    }
};

To clarify, the above code is for ASP.NET MVC. If you're using Web API, then you can just return the data object, or use an IHttpActionResult. The anonymous type part (the new {}) stays the same.

andypaxo
  • 6,171
  • 3
  • 38
  • 53
  • @petelids Yep. You don't even need to wrap it in a `JsonResult` if you're using Web API, just return the object (or wrap it in an `IHttpActionResult`) – andypaxo Apr 16 '15 at 16:58
  • Won't it fail if the Accept header is 'application/xml' as the anonymous object won't be serializable? – petelids Apr 16 '15 at 18:09
  • Yes, it will fail if the client requests XML. This is just for returning JSON. (However, if you do know a way of making it work for XML, please do add it to the answer). – andypaxo Apr 16 '15 at 18:35
  • There's a question about forcing Json to be returned [here](http://stackoverflow.com/questions/12629144/how-to-force-asp-net-web-api-to-always-return-json). I won't edit your answer as it's a good answer as it is and from the sounds of it the OP is in control of the caller. – petelids Apr 16 '15 at 21:01
3

Use an anonymous object.

public object Get(string id)
{
    // do some SQL querying here to grab the model or what have you.

    if (somethingGoesWrong = true)
    return new {result = "fail"}
    else
    return new {result = "success", value= "some value goes here"}
}
Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
1

You can use a generic JObject to return your values without constructing a complete class structure as shown below

public JObject Get(int id)
    {

        return JsonConvert.DeserializeObject<JObject>(@"{""result"":""success"",""value"":""some value goes here""}");


    }
Praveen Paulose
  • 5,741
  • 1
  • 15
  • 19
1

For hard coded response, why not just do something like below. The JSON content will be returned without being surrounded by quotation marks.

    public HttpResponseMessage Get()
    {
        string content = "Your JSON content";
        return BuildResponseWithoutQuotationMarks(content);
    }

    private HttpResponseMessage BuildResponseWithoutQuotationMarks(string content)
    {
        var response = Request.CreateResponse(HttpStatusCode.OK);
        response.Content = new StringContent(content);
        return response;
    }

    private HttpResponseMessage BuildResponseWithQuotationMarks(string content)
    {
        var response = Request.CreateResponse(HttpStatusCode.OK, content);
        return response;
    }
user3613932
  • 1,219
  • 15
  • 16
  • Best answer for my use case. – Bryan Rayner Oct 19 '16 at 19:07
  • This will return as `text/plain`. If you still want to return as `application/json`, you need to add this: `response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");` – Peter Mar 23 '17 at 09:23
0
// GET: api/ReturnJSON
public JsonResult Get()
{
   return Json(new { Property1 = "Value1", Property2 = "Value2" });
}

You can return json using JsonResult class. and the Json() method takes anonymous object so you don't need to create a class.

Community
  • 1
  • 1
Bilal Fazlani
  • 6,727
  • 9
  • 44
  • 90