Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
185 views
in Technique[技术] by (71.8m points)

c# - 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
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...