C#对象转换Json时的一些高级用法

[JsonObject(MemberSerialization.OptIn)]   //默认为不输出
public class PeopleInfo
{ 
     [JsonProperty]   //需要输出 
     public string Name { get; set; } 
     [JsonProperty]   //需要输出 
     public int Age { get; set; } 
     public DateTime Birthday { get; set; } 
     public EnumGender Gender { get; set; } 
     public List<string> Hobby { get; set; } 
}

【OptIn情况下,默认是将所有的属性都定义成了不要输出,如果这个属性需要转换成Json,需要标记JsonProperty】

转换后的结果:

{
   "Name" : "Tom",
   "Age": 20
}
[JsonObject(MemberSerialization.OptOut)]   //默认为全输出
public class PeopleInfo
{
    public string Name { get; set; } 
    [JsonIgnore]  //不需输出
    public int Age { get; set; }
    [JsonIgnore]   //不需输出
    public DateTime Birthday { get; set; }
    public EnumGender Gender { get; set; }
    public List<string> Hobby { get; set; }
}

【OptOut情况下,默认是将所有的属性都定义成了要转换Json,如果这个属性不需要转换成Json,需要标记JsonIgnore】

转换后的结果:

{
  "Name": "Tom",
  "Gender": 1,
  "Hobby" :["写生","钓鱼","旅行"]
}

1. 序列化时更改(重命名)属性名称

public class PeopleInfo
{
     [JsonProperty(PropertyName = "名称")] //写法1
     public string Name { get; set; }            
     [JsonProperty("年龄")]   //写法2
     public int Age { get; set; }
     public DateTime Birthday { get; set; }
     public EnumGender Gender { get; set; }
     public List<string> Hobby{ get; set; }
}

转换后的结果:

{
  "名称": "Tom",
  "年龄": 20,
  "Birthday": "2002-01-01",
  "Gender": 1,
  "Hobby" :["写生","钓鱼","旅行"]
}

2. 序列化时将非公共变量(private)转换为Json

public class PeopleInfo
{
     private string Name { get; set; }       
     public int Age { get; set; }     
     public DateTime Birthday { get; set; }
     public EnumGender Gender { get; set; }
     public List<string> Hobby { get; set; }
}

一般情况下,在进行Json转换的时候,只会对public 成员进行Json转换,默认情况下,私有成员是不转换的。

转换后的结果:

{
  "Age": 20,
  "Birthday": "2002-01-01",
  "Gender": 1,
  "Hobby" :["写生","钓鱼","旅行"]
}

在private成员属性上标记[JsonProperty]

public class PeopleInfo
{
    [JsonProperty]
    private string Name { get; set; }       
    public int Age { get; set; }     
    public DateTime Birthday { get; set; }
    public EnumGender Gender { get; set; }
    public List<string> Hobby { get; set; }
}

转换后的结果:

{
  "Name":null,
  "Age": 20,
  "Birthday": "2002-01-01",
  "Gender": 1,
  "Hobby" :["写生","钓鱼","旅行"]
}

3. 序列化时忽略空值的属性字段

上面的例子中,Name字段为Null值,假如实际前后端数据交互中,Null值的数据返回岂不是很没有意义?为此,我们可以设置下,如果值为Null值时,就不进行序列化转换。

public class PeopleInfo
{
    [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
     private string Name { get; set; }       
     public int Age { get; set; }     
     public DateTime Birthday { get; set; }
     public EnumGender Gender { get; set; }
     public List<string> Hobby { get; set; }
}

转换后的结果:

{  
  "Age": 20,
  "Birthday": "2002-01-01",
  "Gender": 1,
  "Hobby" :["写生","钓鱼","旅行"]
}

【NullValueHandling:这是每个枚举值,Ignore忽略空值,Include包含空值】

通过上面的示例,我们可以发现,可以对单个属性进行设置,如果一个实体类有几十个属性成员,然后,一个一个去设置岂不是很不方便,有没有更高效的方式呢?这个方式就不需要在单独对每一个属性进行设置了。

private void btnJsonDemo_Click(object sender, EventArgs e)
{
     PeopleInfo p = new PeopleInfo();
     //p.Name = "Tom";   //没有对Name属性赋值,Name值为Null值
     p.Age = 20;
     p.Birthday = DateTime.Now.Date;
     p.Gender = EnumGender.male;
     p.Hobby = new List<string> { "写生", "钓鱼", "旅行" };
JsonSerializerSettings setting
= new JsonSerializerSettings(); setting.NullValueHandling = NullValueHandling.Ignore; //设置全局的Null值处理 string json = JsonConvert.SerializeObject(p, setting); this.txtResult.Text = json; }

转换后的结果:

{  
  "Age": 20,
  "Birthday": "2002-01-01",
  "Gender": 1,
  "Hobby" :["写生","钓鱼","旅行"]
}

4. 序列化时枚举值的处理

在上面的例子中,所转换的Gender都是int类型的,假如,我们在转换Json时需要转换成对应的字符怎么操作呢?

public class PeopleInfo
{      
    private string Name { get; set; }       
    public int Age { get; set; }     
    public DateTime Birthday { get; set; }
    //指定Enum类型的转换方式
    [JsonConverter(typeof(StringEnumConverter))]
    public EnumGender Gender { get; set; }
    public List<string> Hobby { get; set; }
}

public Enum EnumGender 
{
    Woman,
    Male
}

转换后的结果:

{  
  "Age": 20,
  "Birthday": "2002-01-01",
  "Gender": "Male"
  "Hobby" :["写生","钓鱼","旅行"]
}

5. 根据条件来设置属性是否序列化

Json.NET能够通过在类上放置ShouldSerialize方法来有条件地序列化属性,要有条件地序列化属性,需要在对象类中增加一个与该属性同名的布尔值的方法,然后使用ShouldSerialize作为方法名称的前缀,比如你要设置属性字段Name根据条件来动态决定是否序列化,则方法名一定要写成ShouldSerializeName()。方法的返回值必须是bool类型,如果返回true,表示这个属性可以序列化,返回false表示不被序列化。

还用以前的PeopleInfo 类,稍微改进下:

public class PeopleInfo
{      
    private string Name { get; set; }       
    public int Age { get; set; }     
    public DateTime Birthday { get; set; }   
    public EnumGender Gender { get; set; }
    public List<string> Hobby { get; set; }

     //注意方法名称以及方法类型
    public bool ShouldSerializeName()
    {
        if (this.Name == "Tom")  //如果名称是Tom,则Name属性不序列化
                return false;
            return true;
    }
}

调用方法:

List<PeopleInfo> list = new List<PeopleInfo>();
PeopleInfo p = new PeopleInfo();
p.Name = "Tom";
p.Age = 20;
p.Birthday = DateTime.Now.Date;
p.Gender = EnumGender.male;
p.Hobby = new List<string> { "写生", "钓鱼", "旅行" };
list.Add(p);
 
PeopleInfo p1 = new PeopleInfo();
p1.Name = "Jack";
p1.Age = 30;
p1.Birthday = DateTime.Now.Date;
p1.Gender = EnumGender.male;
p1.Hobby = new List<string> { "工作" };
ist.Add(p1);
 
string json = JsonConvert.SerializeObject(list);
this.txtResult.Text = json;

转换结果为:

{  
  "Age": 20,
  "Birthday": "2002-01-01",
  "Gender": 1,
  "Hobby" :["写生","钓鱼","旅行"]
},
{  
  "Name":"Jack",
  "Age": 30,
  "Birthday": "2002-01-01",
  "Gender": 1,
  "Hobby" :["工作"]
}

6. 根据条件来设置多个属性是否序列化

针对上面的问题,如果有多个属性需要根据条件来序列化怎么办?我们可以新增一个方法,如下:

public class LimitPropsContractResolver : DefaultContractResolver
{
        string[] Propertys = null;
        bool IsSerialize;
        public LimitPropsContractResolver(string[] props, bool retain = true)
        {
            this.Propertys = props;
            this.IsSerialize = retain;
        }
        protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
        {
            IList<JsonProperty> list = base.CreateProperties(type, memberSerialization);
            return list.Where(p =>
            {
                if (IsSerialize)
                {
                    return Propertys.Contains(p.PropertyName);
                }
                else
                {
                    return !Propertys.Contains(p.PropertyName);
                }
            }).ToList();
        }
}

调用的时候,只需要把字段名称传入string数组中就可以,bool值表示是否需要转换此字段;调用方法如下:

JsonSerializerSettings settings = new JsonSerializerSettings();
settings.ContractResolver = new LimitPropsContractResolver(new string[] { "Gender", "Hobby" }, false);
string json = JsonConvert.SerializeObject(list, settings);

 

posted @ 2024-07-16 15:34  每天进步多一点  阅读(1)  评论(0编辑  收藏  举报