As others have pointed out, you need to create a formatter and replace the DataContractSerializer
with a JSON.NET
serializer. Although, if you are not in a hurry specifically for JSON.NET, there are rumors that the next beta / rc will support native JSON.NET.
Conceptually, however, you are missing a piece of WebAPI magic. Using WebAPI, you return your object to its native state (or IQueryable if you want OData support). After your function call completes, Formatter will take over and convert it to the desired form based on the clientโs request.
So, in your source code, you converted PTE_Test
to a JSON string and returned it, after which the JSON Formatter launched and serialized the string. I changed your code as follows:
public class PTE_TestsController : ApiController { PTE_TestsRepository _repository = new PTE_TestsRepository(); public HttpResponseMessage<PTE_Test> Get(int id) { try { PTE_Test test = _repository.GetTest(id); return new HttpResponseMessage(test); } catch { return new HttpResponseMessage<string>(HttpStatusCode.NotFound); } } }
Notice how your function returns PTE_Test
instead of string
. Assuming the request came with the Accept = application/json
request header, then JSON formatting will be called. If the request has a heading: Accept = text/xml
, XML formatting is called.
There is a decent article on the topic here . If you're a visual student, Scott Gu shows some examples using the violinist in this video, starting in about 37 minutes . Pedro Reis will go a little deeper into the discussion of content here .
EBarr source share