在Web API控制器中构建JSON响应 [英] Build JSON response in Web API controller

查看:81
本文介绍了在Web API控制器中构建JSON响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在一个WebAPI项目中,我有一个控制器,可以根据用户输入的值来检查产品的状态.

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

让我们说他们输入"123",并且响应应该是状态":1,以及产品列表.如果输入"321",则状态"为0,并显示产品列表.

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.

我的问题是,如何在WebAPI控制器中构建正确的字符串.

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
}

推荐答案

所以这是您的帖子的更改:

So here are the changes for your post:

首先,在传递text/html请求时,您应该默认使api返回Json(这是您要查找的吗?),并将此行添加到您的WebApiConfig类中:

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; }
}

方法主体:

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;
}

这将产生以下示例json:

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.

这篇关于在Web API控制器中构建JSON响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆