JsonConverter.SerializeObject != System.Web.Mvc.JsonResult

Oct 21, 2010 at 8:08 PM

James,

 I am hoping you might be able to explain why JSON.Net is behaving differently than JSON within Microsoft MVC. Because the jsonTree.attr value is getting formatted differently, the jQuery plugin (jsTree) I am using stops working when used within standard ASP.NET (without MVC).

 JsonTreeView is defined as:

   public class JsonTreeView
   {
       public string data;   // "node_title"
       public object attr; // { id : "node_identificator", some-other-attribute : "attribute_value" }, 
       public string state;   // "closed", // or "open", defaults to "closed"
       public object[] children; // [ /* an array of child nodes objects */ ]
   }

When using System.Web.Mvc and JsonResult:

if(id == "0")
{
   jsonTree.data = containerName;
   jsonTree.attr = Json(new { id = URI }).Data;
   jsonTree.state = "closed";
}

The jsonTree.attr value looks like { id = "https://cf-na-east-01.opsourcecloud.net/v2/containers/816CFD76-B453-11DF-A1B3-237F1154DBDB" }

But when I try using JsonConvert.SerializeObject() 

if(id == "0")
{
   jsonTree.data = containerName;
   jsonTree.attr = JsonConvert.SerializeObject(new { id = URI } );
   jsonTree.state = "closed";
}

the jsonTree.attr value ends up looking like "{\"id\":\"https://cf-na-east-01.opsourcecloud.net/v2/containers/816CFD76-B453-11DF-A1B3-237F1154DBDB\"}"

The different formatting is causing the plugin to fail, but I'm not sure why this is happening.  Any insights would be greatly appreciated.

Mark

 

Coordinator
Oct 22, 2010 at 10:43 PM

I'm pretty sure

jsonTree.attr = Json(new { id = URI }).Data;

is exactly the same as

jsonTree.attr = new { id = URI };