如何在返回到客户端之前编辑和更改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**
}
}
答案 0 :(得分:0)
您需要使用例如JsonExSerializer库将JSON反序列化为某种对象。然后,您可以开始修改对象,将其序列化为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);