如何将 ShouldSerialize[MemberName]() 方法用于 Object 类型的属性



我试图使用 Newtonsoft.JSON 中的 ShouldSerialize 方法防止类型对象的属性没有为其属性分配新值。但是我不知道如何实现它,所以请帮助我解决这个问题......

这是示例代码

public class Sample1
 {
   public String name{get;set;}
   public int Id{get;set;}; 
 }

这是我的类,包含上述类作为其属性之一

public class Container
 {
   public String Cname{get;set;}
   public Sample1 Sample{get;set;}; 
   public bool ShouldSerializeSample()
  {
      //What should I write here to prevent the Sample property from being serialized when its properties are assigned no new values.
  }
 }

鉴于您的示例类,我认为您正在寻找这样的东西:

public bool ShouldSerializeSample()
{
    return (Sample != null && (Sample.Id != 0 || Sample.name != null));
}

这是一个工作演示:

class Program
{
    static void Main(string[] args)
    {
        List<Container> list = new List<Container>
        {
            new Container
            {
                Cname = "Will serialize Sample because it has a name",
                Sample = new Sample1 { name = "sample 1" }
            },
            new Container
            {
                Cname = "Will serialize Sample because it has a non-zero Id",
                Sample = new Sample1 { Id = 2 }
            },
            new Container
            {
                Cname = "Will serialize Sample because it has a name and an Id",
                Sample = new Sample1 { name = "sample 3", Id = 3 }
            },
            new Container
            {
                Cname = "Will not serialize Sample because it has default values",
                Sample = new Sample1()
            },
            new Container
            {
                Cname = "Will not serialize Sample because it is null",
                Sample = null
            }
        };
        string json = JsonConvert.SerializeObject(list, Formatting.Indented);
        Console.WriteLine(json);
    }
}
public class Sample1
{
    public String name { get; set; }
    public int Id { get; set; }
}
public class Container
{
    public String Cname { get; set; }
    public Sample1 Sample { get; set; }
    public bool ShouldSerializeSample()
    {
        return (Sample != null && (Sample.Id != 0 || Sample.name != null));
    }
}

这是输出:

[
  {
    "Cname": "Will serialize Sample because it has a name",
    "Sample": {
      "name": "sample 1",
      "Id": 0
    }
  },
  {
    "Cname": "Will serialize Sample because it has a non-zero Id",
    "Sample": {
      "name": null,
      "Id": 2
    }
  },
  {
    "Cname": "Will serialize Sample because it has a name and an Id",
    "Sample": {
      "name": "sample 3",
      "Id": 3
    }
  },
  {
    "Cname": "Will not serialize Sample because it has default values"
  },
  {
    "Cname": "Will not serialize Sample because it is null"
  }
]

相关内容

  • 没有找到相关文章

最新更新