Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Build JSON response in Web API controller

In a WebAPI project, i have a controller that checks a status of a product, based on a value the user enters.

Lets say they enter "123" and the response should be "status": 1, AND a list of products. If they enter "321" the "status" is 0, AND a list of products.

My question is, how do i build such a string correct in a WebAPI controller.

[Route("{value:int}")]
public string GetProducts(int value)
{
    var json = "";
    var products = db.Products;
    if (products.Any())
    {
        foreach (var s in products)
        {
            ProductApi product = new ProductApi();
            product.Name = s.Name;
            json += JsonConvert.SerializeObject(supplier);
        }
    }

    var status = db.Status;
    if (status.Any())
    {
        json += "{status:1}";
    }
    else
    {
        json += "{status:0}";
    }

    return json;
}

public class ProductApi
{
    public string Name { get; set; }
}

Also, is this output/response considered valid?

[
    {
        "id":1,
        "name":"product name"
    },
    {
        "id":2,
        "name":"product name 2"
    },
    {
        "id":3,
        "name":"product name 3"
    }
]

{
    "status": 0
}
like image 361
brother Avatar asked Mar 11 '16 09:03

brother


People also ask

How do I return a JSON response in API?

To return JSON from the server, you must include the JSON data in the body of the HTTP response message and provide a "Content-Type: application/json" response header. The Content-Type response header allows the client to interpret the data in the response body correctly.

What is JSON API response?

JSON:API is a specification for how a client should request that resources be fetched or modified, and how a server should respond to those requests. JSON:API is designed to minimize both the number of requests and the amount of data transmitted between clients and servers.

How can we post data in a JSON format to a Web API from a MVC controller?

You need to use JSON. stringify method to convert it to JSON string when you send it, And the model binder will bind the json data to your class object. contentType property tells the server that we are sending the data in JSON format.


2 Answers

So here are the changes for your post:

First, you should make your api return Json by default when you pass a text/html request (is this you are looking for?), adding this line to your WebApiConfig class:

config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));

Second, I changed the code to return a real object, impersonating your response:

public class ProductApiCollection
{   
    public ProductApi[] Products { get; set; }      
    public byte Status { get; set; }
}

public class ProductApi
{
    public string Name { get; set; }
}

Method body:

public ProductApiCollection Get()
{
    var result = new ProductApiCollection();
    var dbProducts = db.Products;
    var apiModels = dbProducts.Select(x => new ProductApi { Name = x.Name } ).ToArray();
    result.Products = apiModels;

    var status = db.Status.Any() ? 1 : 0;
    result.Status = status;

    return result;
}

This will results in the following example json:

{
  "Products": [
    {
      "Name": "Pork"
    },
    {
      "Name": "Beef"
    },
    {
      "Name": "Chicken"
    },
    {
      "Name": "Salad"
    }
  ],
  "Status": 1
}

I strongly advise you not to do manual formatting for such things, and rely on built-in and 3rd party libraries. Otherwise, you will be reinventing the things already available, tested and ready to work.

like image 135
Red Avatar answered Sep 19 '22 14:09

Red


Just as raderick mentioned, you don't need to create your own custom JSON infrastructure.

public class ProductApi
{
    public int Id {get;set;}
    public string Name { get; set; }
}

public class ResponseDTO
{
    public int Status {get;set;}
    public List<ProductApi> { get; set; }
}

And in your API action, return like this:

[Route("{value:int}")]
public ResponseDTO GetProducts(int value)
{
    ResponseDTO result = ...// construct response here 

    return result;
}
like image 21
Tamas Ionut Avatar answered Sep 19 '22 14:09

Tamas Ionut