Bye
Bye

Reputation: 2806

Working with Json.net and Web API

After much wrangling, I finally got my Json result to work properly in my web api for classes with associations:

    public string GetAll()
    {
        var order =_repository.GetAll();
        var settings = new JsonSerializerSettings
               {
                   ReferenceLoopHandling = ReferenceLoopHandling.Ignore
               };

        return JsonConvert.SerializeObject(order, settings);

    }

But when I test in, either in browser or Fiddler, instead of something typical like:

(A)

     "Books":
        [  
           {    
             "Id": "1",  
             "Name": "Book1", 
             "Authors": 
                [
                  { 
                    ....... 
                  }
               ]  
           } 
       ] 

(B) I get this:

"[{\"Id\":1,\"Name\":\"Book1\",\"Authors\":[{\"Id\":1,\"PersonId\":1,\"Person\":null,\"Books\":[{\"Id\":3,\"Name\":\"Book3\",\"Authors\":[{\"Id\":4,\"PersonId\":4,\"Person\":null,\"Books\":[{\"Id\":2,\"Name\":\"Book2\",\"Authors\":[{\"Id\":2,\"PersonId\":2,\"Person\":null,\"Books\": .....

Can someone kindly tell me what I must do to format it like A. above?

Thanks

Update:

BTW, Formatting.Indented made it worse:

"[\r\n {\r\n \"Id\": 1,\r\n \"Name\": \"Book1\",\r\n \"Authors\": [\r\n {\r\n \"Id\": 1,\r\n \"PersonId\": 1,\r\n \"Person\": {\r\n \"Id\": 1,\r\n \"FirstName\": \"John\",\r\n \"LastName\": \"Doe\"\r\n },\r\n \"Books\": [\r\n {\r\n \"Id\": 3,\r\n \"Name\": \"Book3\",\r\n \"Authors\": [\r\n {\r\n \"Id\": 4,\r\n \"PersonId\": 4,\r\n \"Person\": {\r\n \"Id\": 4,\r\n \"FirstName\": \"Julie\",\r\n

Upvotes: 0

Views: 1614

Answers (3)

jvhang
jvhang

Reputation: 777

I think the issue here is that the JSON is being serialized twice, once by you, and again by WebAPI. Remove your serialization and all should be fine.

Upvotes: 0

Chris
Chris

Reputation: 772

The traditional approach is that your API controller returns either an HttpResponseMessage or a collection object, but not the already serialised object. The MediaTypeFormatter objects will take care of that for you.

What looks to be happening is that your controller is returning a string which is then being converted into a JSON representation (because of the MediaTypeFormatter for JSON). Try changing your controller to just return the object collection (without serialising it to a string) and it should work for you.

Upvotes: 2

Kiran
Kiran

Reputation: 57949

settings.Formatting = Formatting.Indented;

just curious...any reason why you are using JsonMediaTypeFormatter to handle writing the response?...i see that you are serializing it explicitly to json...

Upvotes: 0

Related Questions