简体   繁体   中英

Web API C# - Returning full KVC Json

I am using RestKit from an iOS app to connect to a Web API service that we are building in C# .Net 4.

I am having the same issue from here: RestKit non-kvc object mapping

Basically C# returns something like:

formatted raw 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"
}
]

While the standard format expected by RestKit is

{"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"
}
]

I don't care using a way or another, however, it seems that it would be easier from the iOS side to make C# return the "customers" class name.

How can I tell C# to return that?

Thanks.

This is the current code in my ApiController in C#:

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

I've had some issues like this when trying to serialize JSON in C#. I think the easiest way is wrap the customer in another class. If you only need to serialize in one place you can do something like var temp = new Object { customer customer = new customer(); } var temp = new Object { customer customer = new customer(); } right before making the call to serialize it.

This is the best solution I have found so far. Basically replace the IEnumerable by HttpResponseMessage and use the Request.CreateResponse to respond (code below).

While it works it is less than ideal: I lose the abstraction, and now the controller respond with Json regardless of the request headers (that logic was resolved automatically, but when using the CreateResponse I am writing directly to the output).

// 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() });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM