how to remove $id during JSON serialization

前端 未结 6 1821
萌比男神i
萌比男神i 2020-12-01 09:22

I am using NewtonSoft.JSON. When running

JsonConvert.SerializeObject(myObject)

it is adding an

6条回答
  •  长情又很酷
    2020-12-01 09:36

    To remove the $id in JSON for my web API. I included [JsonObject(IsReference = false)] for my class objects and [JsonProperty(IsReference = false)] for my properties that are of object types. In my case the RespObj property is generic Type T and could take any object type I pass to it including collections so I had to use [JsonProperty(IsReference = false)] to get rid of the $id in the serialized JSON string.

    I did not change my WebApiConfig because I was using the MVC help page for WEB API and it required me to have this configuration in my webApiconfig:

    var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
            json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.All;
            json.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize;
    

    The class object

    [DataContract(IsReference = true)]
    [JsonObject(IsReference = false)]
    public class QMResponse where T : new()
    {
        public QMResponse()
        {
    
        }
    
        /// 
        /// The response code
        ///  
        public string RespCode { get; set; }
    
        /// 
        /// The response message
        ///  
        public string RespMxg { get; set; }
    
        /// 
        /// The exception message
        ///  
        public string exception { get; set; }
    
        /// 
        /// The object type returned
        ///          
        [JsonProperty(IsReference = false)]
        public T RespObj { get; set; }
    
        /// 
        /// No of records returned
        ///  
        public long RecordCount { get; set; }
    
        /// 
        /// The Session Object
        ///  
        public string session_id { get; set; }
    
    }
    

提交回复
热议问题