7

I use Metadata and JsonIgnore to remove special field from being serializing.

[Authorize(Roles = "admin")]
public class UserController : ApiController
{
    public IEnumerable<user> Get()
    {
        using (var mydb = new ModelContainer())
        {
            return mydb.userSet.ToList();
        }
    }
}

[MetadataType(typeof(user_Metadata))]  
public partial class user
{  
    private class user_Metadata  
    {  
        [JsonIgnore]  
        public virtual password { get; set; }  

        public virtual adminFile { get; set; }  
    }  
}  

How can I dynamic control which field should be serialized or not. For some thing like

public partial class user
{  
    private class user_Metadata  
    {  
        [JsonIgnore]  
        public virtual password { get; set; }  
        [Roes == admin?JsonIgnore:JsonNotIgnore] //some thing like this
        public virtual adminFile { get; set; }  
    }  
} 
T_T
  • 515
  • 1
  • 7
  • 16

2 Answers2

10

Conditional property serialization

James Newton-King
  • 48,174
  • 24
  • 109
  • 130
0

JsonIgnore is a property which can't be set dynamically. But you can try something similar like this.

public partial class user
{  
    private class user_Metadata  
    {  
        [JsonIgnore]  
        public virtual password { get; set; }  

        //[Roes == admin?JsonIgnore:JsonNotIgnore] //something like this
        public virtual adminFile 
        { 
            get
            {
               if(Roes == admin)
                   return NULL;
               else
                   return adminFile;
            }
            set
            {
               if(Roes == admin)
                   value = NULL;
               else
                   value = adminFile;
            } 
        }  

    }  
} 

By this way, You can save the default value instead of saving the actual value for a property.

Juan
  • 4,910
  • 3
  • 37
  • 46
Murugan
  • 1,441
  • 1
  • 12
  • 22
  • 1
    thank you, this can get things to work.But I'd like to the way in json.net like James said – T_T Apr 23 '13 at 01:08