Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Json.Encode() use JavaScriptSerializer Class to serialize

Does the Json.Encode() Helper use the JavaScriptSerializer class to encode a string to json?

I am getting a circular reference exception when using Json.Encode(Model) even though my class properties that are being serialized have the [ScriptIgnore] attribute.

My only guess is that maybe the Json.Encode() helper doesn't use the JavaScriptSerializer to serialize to json but I can't find the documentation anywhere on msdn.

@Html.Raw(Json.Encode(Model))

Here's an example of one of the models that has a property that should not be serialized...

using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Web.Script.Serialization;

namespace RobotDog.Entities {
    public class Character {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int Id { get; set; }

        [MaxLength(200)]
        public string Name { get; set; }

        public virtual Person Person { get; set; }

        [ScriptIgnore]
        public virtual Movie Movie { get; set; }
    }
}
like image 884
bflemi3 Avatar asked Jan 25 '13 02:01

bflemi3


1 Answers

Does the Json.Encode() Helper use the JavaScriptSerializer class to encode a string to json?

Yes.

From the source code:

private static readonly JavaScriptSerializer _serializer = Json.CreateSerializer();

public static string Encode(object value)
{
  DynamicJsonArray dynamicJsonArray = value as DynamicJsonArray;
  if (dynamicJsonArray != null)
    return Json._serializer.Serialize((object) (object[]) dynamicJsonArray);
  else
    return Json._serializer.Serialize(value);
}

where JavaScriptSerializer is System.Web.Script.Serialization.JavaScriptSerializer

also to assist your issue see this thread

like image 144
wal Avatar answered Oct 20 '22 19:10

wal