Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using the Json.NET serializer in an MVC4 project

I'm starting to learn Json.NET, but I'm having trouble using its serializer. I have a new MVC4 project with a Web.API service:

public class PTE_TestsController : ApiController {

  PTE_TestsRepository _repository = new PTE_TestsRepository();

  // GET /api/PTE_Tests/5
  public HttpResponseMessage<string> Get(int id) {
    try {
       PTE_Test test = _repository.GetTest(id);
       return new HttpResponseMessage<string>(JsonConvert.SerializeObject(test));
    } catch {
       return new HttpResponseMessage<string>(HttpStatusCode.NotFound);
    }
  }
}

JsonConvert.SerializeObject() works as expected and returns a string. My Web.API controller returns that as part of an HttpResponseMessage. The end result, when viewed in Fiddler, is not JSON data, but JSON data being serialized again (I think):

"{\"ID\":1,\"Name\":\"Talar Tilt\",\"TagID\":1,\"PracticeID\":1,
   \"SpecificAreaID\":1,\"TypeID\":1,\"VideoID\":1,\"PicID\":1}"

Does someone know how to turn off the default serializer so I can use Json.NET directly? By the way, I'm not using the default serializer because I can't figure out how to make it work with complex objects (PTE_Test will eventually contain members of type List).

Alternately, it will also solve my problem if someone can explain how to use the default serializer with complex objects. MSDN's explanation didn't help me.

like image 780
CraigB Avatar asked Apr 20 '12 18:04

CraigB


1 Answers

Rick Strahl has a blog on that here with a code that works.

like image 182
Aliostad Avatar answered Nov 15 '22 08:11

Aliostad