5

Is it possible to use PetaPoco dynamic query to return Json in the ASP.net WebAPI?

//WebAPI Controller

public class BranchController : ApiController
{
    public IEnumerable<dynamic> Get()
    {
        // Create a PetaPoco database object
        var db = new PetaPoco.Database("DefaultConnection");

        // Show all Branches
        var b = db.Query<dynamic>("SELECT * FROM Branches").ToList();

        return b;
    }

}

I am receiving an error

To be XML serializable, types which inherit from IEnumerable must have an implementation of Add(System.Object)

MHop
  • 3,053
  • 3
  • 17
  • 13
  • I've never used PetaPoco, but have you tried converting returned objects to dynamic JsonObject or JsonArray instances ? http://goo.gl/BaIx5 – cecilphillip Apr 19 '12 at 04:15

2 Answers2

2

JSON.Net handles this out of the box, so I Had to add a Custom Formatter.

This is the MSDN article I used to resolve the issue: http://code.msdn.microsoft.com/Using-JSONNET-with-ASPNET-b2423706

MHop
  • 3,053
  • 3
  • 17
  • 13
0

Since PetaPoco returns a List<dynamic> the real answer here is "Can WebApi return a Json from a List"?

The answer is yes, but WebApi has a thing called Content Negotiation than return Json or XML based on the request.

Try requesting Json or try this for XML:

    // Show all Branches
    return (IEnumerable<dynamic>)db.Query<dynamic>("SELECT * FROM Branches");
Eduardo Molteni
  • 38,786
  • 23
  • 141
  • 206