WebApi 在 JSON 响应中添加类名

huangapple go评论65阅读模式
英文:

WebApi add class name in json response

问题

[
Data:{
"ID": 1,
"BillToName": "Kurian",
"ClientName": "Fort Myers",
"ClientCode": " C00687",
"InvoiceNumber": "INV2484899",
"InvoiceDate": "2023-05-18T00:00:00",
"InvoiceDueDate": "2023-06-17T00:00:00",
"AmountDue": " $110.00",
"OFFC": "FTM",
"DateImported": "2023-05-18T00:00:00",
"DaysFromDueDate": 30
},
{
"ID": 2,
"BillToName": "Levine",
"ClientName": "Fort Lauderdale",
"ClientCode": " C00686",
"InvoiceNumber": "INV2445218",
"InvoiceDate": "2023-04-04T00:00:00",
"InvoiceDueDate": "2023-05-04T00:00:00",
"AmountDue": " $570.00",
"OFFC": "FTL",
"DateImported": "2023-05-19T00:00:00",
"DaysFromDueDate": 30
}
]
英文:

I've been looking all over the place for a way to add the name of the class to the json response from my API. This my first attempt at creating an API, so please any help would be appreciated.

From my Data layer

public static List<Invoices> GetAllInvoices()
        {
            List<Invoices> inslist = new List<Invoices>();
            using (SqlConnection con = new SqlConnection(Connection.sql))
            {
                SqlCommand cmd = new SqlCommand("_Sp_GetOperationsInvoices", con);
                cmd.CommandType = CommandType.StoredProcedure;

                try
                {
                    con.Open();
                    cmd.ExecuteNonQuery();

                    using (SqlDataReader dr = cmd.ExecuteReader())
                    {
                        while (dr.Read())
                        {
                            inslist.Add(new Invoices()
                            {
                                ID = Convert.ToInt32(dr["ID"]),
                                BillToName = dr["BillToName"].ToString(),
                                ClientName = dr["ClientName"].ToString(),
                                ClientCode = dr["ClientCode"].ToString(),
                                InvoiceNumber = dr["InvoiceNumber"].ToString(),
                                InvoiceDate = DateTime.Parse(dr["InvoiceDate"].ToString()),
                                InvoiceDueDate = DateTime.Parse(dr["InvoiceDueDate"].ToString()),
                                AmountDue = dr["AmountDue"].ToString(),
                                OFFC = dr["OFFC"].ToString(),
                                DateImported = DateTime.Parse(dr["DateImported"].ToString()),
                                DaysFromDueDate = int.Parse(dr["DaysFromDueDate"].ToString()),
                            });
                        }
                    }
                    return inslist;
                }
                catch (Exception ex)
                {
                    return inslist;
                }
            }
        }

From my Controller

[HttpGet]
        [Route("api/GetAllInvoices")]
        public List<Invoices> GetAll()
        {           
            var Data = Data_Layer.GetAllInvoices();
            return Data;
        }

The models

public class Records
    {
        public List<Invoices> invoices { get; set; }
    }
    public class Invoices
    {
        public int ID { get; set; }

        public string BillToName { get; set; }

        public string ClientName { get; set; }

        public string ClientCode { get; set; }

        public string InvoiceNumber { get; set; }

        public DateTime? InvoiceDate { get; set; }

        public DateTime? InvoiceDueDate { get; set; }

        public string AmountDue { get; set; }

        public string OFFC { get; set; }

        public DateTime? DateImported { get; set; }

        public int? DaysFromDueDate { get; set; }
    }

Right now the response looks like the following:

[
{
"ID": 1,
"BillToName": "Kurian",
"ClientName": "Fort Myers",
"ClientCode": " C00687",
"InvoiceNumber": "INV2484899",
"InvoiceDate": "2023-05-18T00:00:00",
"InvoiceDueDate": "2023-06-17T00:00:00",
"AmountDue": " $110.00",
"OFFC": "FTM",
"DateImported": "2023-05-18T00:00:00",
"DaysFromDueDate": 30
},
{
"ID": 2,
"BillToName": "Levine",
"ClientName": "Fort Lauderdale",
"ClientCode": " C00686",
"InvoiceNumber": "INV2445218",
"InvoiceDate": "2023-04-04T00:00:00",
"InvoiceDueDate": "2023-05-04T00:00:00",
"AmountDue": " $570.00",
"OFFC": "FTL",
"DateImported": "2023-05-19T00:00:00",
"DaysFromDueDate": 30
}
]

I would like it to be

[
Data:{
"ID": 1,
"BillToName": "Kurian",
"ClientName": "Fort Myers",
"ClientCode": " C00687",
"InvoiceNumber": "INV2484899",
"InvoiceDate": "2023-05-18T00:00:00",
"InvoiceDueDate": "2023-06-17T00:00:00",
"AmountDue": " $110.00",
"OFFC": "FTM",
"DateImported": "2023-05-18T00:00:00",
"DaysFromDueDate": 30
},
{
"ID": 2,
"BillToName": "Levine",
"ClientName": "Fort Lauderdale",
"ClientCode": " C00686",
"InvoiceNumber": "INV2445218",
"InvoiceDate": "2023-04-04T00:00:00",
"InvoiceDueDate": "2023-05-04T00:00:00",
"AmountDue": " $570.00",
"OFFC": "FTL",
"DateImported": "2023-05-19T00:00:00",
"DaysFromDueDate": 30
}
]

答案1

得分: 0

The simplest workaround would be to just simply use a dictionary.
For example:

public IDictionary<string, T> Helper<T>(T obj)
{
    return new Dictionary<string, T>() { { obj?.GetType().Name ?? "null", obj } };
}

usage example:

public dynamic Get()
{
    return Helper(new Test());
}

Output:

{
  "Test": {
    "id": 1,
    "name": "test",
    "x": 1.11
  }
}
英文:

The simplest workaround would be to just simply use a dictionary.
For example:

public IDictionary&lt;string, T&gt; Helper&lt;T&gt;(T obj)
{
	return new Dictionary&lt;string, T&gt;() { { obj?.GetType().Name ?? &quot;null&quot;, obj } };
}

usage example:

public dynamic Get()
{
	return Helper(new Test());
}

Output:

{
  &quot;Test&quot;: {
    &quot;id&quot;: 1,
    &quot;name&quot;: &quot;test&quot;,
    &quot;x&quot;: 1.11
  }
}

答案2

得分: 0

你必须将输出操作更改为IActionResult,并为创建添加一个名为"Data"的模型。

 public IActionResult GetAll()
    {
        var Data = Data_Layer.GetAllInvoices();

        var model = new
        {
            Data = Data
        };
        return Ok(model);
    }
英文:

You must Change Output Action To IActionResult and Create A Model For Create Prefix "Data"

 public IActionResult GetAll()
    {
        var Data = Data_Layer.GetAllInvoices();

        var model = new
        {
            Data = Data
        };
        return Ok(model);
    }

huangapple
  • 本文由 发表于 2023年6月1日 06:07:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/76377584.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定