自定义 ASP.Net Web API 中的 JSON 返回数据

问题描述 投票:0回答:1

如何在 ASP.NET Web API 返回的 JSON 返回给客户端之前对其进行编辑和更改? 例如:

public HttpResponseMessage GetCustomerById(int customerId)
{
    Customer customer = DAL.GetCustomer(123);

    if (customer == null)
    {
        return Request.CreateResponse(HttpStatusCode.NotFound, "Could not find                                        customer " + customerId.ToString());
    }
    else
    {
        return Request.CreateResponse(HttpStatusCode.OK, customer);
         **//  Here I like to edit the JSON before I return it**
    }
}
c# asp.net .net asp.net-web-api
1个回答
0
投票

您需要将 JSON 反序列化为某种对象,例如使用 JsonExSerializer 库。然后,您可以开始修改对象,将其序列化回 JSON 并发送修改后的 JSON 字符串。使用 JsExSer 的示例。

Serializer ser = new Serializer(typeof(ArrayList));
ArrayList json = ser.Deserialize(jsonstring);
json.Add("something");
string jsonready = ser.Serialize(json);

还要注意,修改必须在返回前完成,即:

**//  Here I like to edit the JSON before I return it**
return Request.CreateResponse(HttpStatusCode.OK, customer);
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.