Web API C# - 返回完整的KVC Json

时间:2012-10-29 04:23:20

标签: c# json restkit asp.net-web-api

我正在使用iOS应用中的RestKit连接到我们在C#.Net 4中构建的Web API服务。

我在这里遇到同样的问题:RestKit non-kvc object mapping

基本上C#返回的内容如下:

格式化原始 BODY

[
{
 "Id":6,
 "Guid":"00000000-0000-0000-0000-000000000000",
 "Owner":null,
 "Message":"Testing Wom#10",
 "HashTags":null,
 "createdtime":"2012-10-28T00:00:00",
 "PlayedCount":100,
 "DurationInSecs":150.0,
 "FileSizeInBytes":20000,
 "FileUrl":"http://www.wom.com"
}
]

虽然RestKit期望的标准格式是

{"woms": [
{
 "Id":6,
 "Guid":"00000000-0000-0000-0000-000000000000",
 "Owner":null,
 "Message":"Testing Wom#10",
 "HashTags":null,
 "createdtime":"2012-10-28T00:00:00",
 "PlayedCount":100,
 "DurationInSecs":150.0,
 "FileSizeInBytes":20000,
 "FileUrl":"http://www.wom.com"
}
]

我并不关心使用某种方式,但是,似乎从iOS端更容易让C#返回“customers”类名。

如何告诉C#返回?

感谢。

这是我在C#中的ApiController中的当前代码:

namespace WomWeb.Controllers.Apis
{
[Authorize]
public class WomsController : ApiController
{
    private WomContext db = new WomContext();

    // GET api/Woms
    public IEnumerable<Wom> GetWoms()
    {
        return db.Woms.AsEnumerable();            
    }

2 个答案:

答案 0 :(得分:1)

在尝试使用C#序列化JSON时,我遇到了类似的问题。我认为最简单的方法是将客户包装在另一个类中。如果您只需要在一个地方序列化,则可以在调用序列化之前执行var temp = new Object { customer customer = new customer(); }之类的操作。

答案 1 :(得分:0)

这是我迄今为止找到的最佳解决方案。基本上用HttpResponseMessage替换IEnumerable并使用Request.CreateResponse来响应(代码如下)。

虽然它有效但它不太理想:我失去了抽象,现在控制器响应Json而不管请求标头(逻辑是自动解决的,但是当使用CreateResponse我直接写入输出时)。

// GET api/Woms           
//public IEnumerable<Wom> GetWoms()
public HttpResponseMessage GetWoms()
{
  //return  db.Woms.Include("Owner").AsEnumerable(); 
  return Request.CreateResponse(HttpStatusCode.OK, new { woms = Include("Owner").AsEnumerable() });
}