MVC3 JSON Serialization: How to control the property names?

后端 未结 2 609
天涯浪人
天涯浪人 2020-12-10 03:41

I want to serialize a simple object to JSON:

public class JsonTreeNode
{
    [DataMember(Name = \"title\")]
    public string Title { get; set; }

    [DataM         


        
2条回答
  •  南方客
    南方客 (楼主)
    2020-12-10 04:12

    I solved the problem by using the technique provided in the answer in this question:

    ASP.NET MVC: Controlling serialization of property names with JsonResult

    Here is the class I made:

    /// 
    /// Similiar to , with
    /// the exception that the  attributes are
    /// respected.
    /// 
    /// 
    /// Based on the excellent stackoverflow answer:
    /// https://stackoverflow.com/a/263416/1039947
    /// 
    public class JsonDataContractActionResult : ActionResult
    {
        /// 
        /// Initializes a new instance of the class.
        /// 
        /// Data to parse.
        public JsonDataContractActionResult(Object data)
        {
            Data = data;
        }
    
        /// 
        /// Gets or sets the data.
        /// 
        public Object Data { get; private set; }
    
        /// 
        /// Enables processing of the result of an action method by a 
        /// custom type that inherits from the ActionResult class. 
        /// 
        /// The controller context.
        public override void ExecuteResult(ControllerContext context)
        {
            if (context == null)
                throw new ArgumentNullException("context");
    
            var serializer = new DataContractJsonSerializer(Data.GetType());
    
            string output;
            using (var ms = new MemoryStream())
            {
                serializer.WriteObject(ms, Data);
                output = Encoding.UTF8.GetString(ms.ToArray());
            }
    
            context.HttpContext.Response.ContentType = "application/json";
            context.HttpContext.Response.Write(output);
        }
    }
    

    Usage:

        public ActionResult TestFunction()
        {
            var testObject = new TestClass();
            return new JsonDataContractActionResult(testObject);
        }
    

    I also had to modify the initial class:

    // -- The DataContract property was added --
    [DataContract]
    public class JsonTreeNode
    {
        [DataMember(Name = "title")]
        public string Title { get; set; }
    
        [DataMember(Name = "isFolder")]
        public bool IsFolder { get; set; }
    
        [DataMember(Name = "key")]
        public string Key { get; set; }
    
        [DataMember(Name = "children")]
        public IEnumerable Children { get; set; }
    
        [DataMember(Name = "select")]
        public bool SelectedOnInit { get; set; }
    }
    

提交回复
热议问题