代码之家  ›  专栏  ›  技术社区  ›  Mert Altiparmak

如何在c#中创建和转换json一个属性较少的类?复制

  •  0
  • Mert Altiparmak  · 技术社区  · 1 年前

    我们正在开发一个c#api项目。我们想序列化一个有3个属性的类,但这个类里面有10个属性。 如何创建和转换具有3个属性的json类? 我想用这个3属性生成一个json字符串。

    public class SampleClass
    {
    public string Prop1 { get; set; }
    public string Prop2 { get; set; }
    public string Prop3 { get; set; }
    public string Prop4 { get; set; }
    public string Prop5 { get; set; }
    public string Prop6 { get; set; }
    public string Prop7 { get; set; }
    public string Prop8 { get; set; }
    public string Prop9 { get; set; }
    public string Prop10 { get; set; }
    }
    
    var myObj = new MyClass
        {
            Prop1 = "Value 1",
            Prop2 = "Value 2",
            Prop3 = "Value 3"
        };
    
    1 回复  |  直到 1 年前
        1
  •  1
  •   Michał Turczyn    1 年前

    你可以使用 JsonIgnoreAttribute :

    public class SampleClass
    {
        public string Prop1 { get; set; }
    
        public string Prop2 { get; set; }
    
        public string Prop3 { get; set; }
    
        [JsonIgnore]
        public string Prop4 { get; set; }
    
        [JsonIgnore]
        public string Prop5 { get; set; }
    
        [JsonIgnore]
        public string Prop6 { get; set; }
    
        [JsonIgnore]
        public string Prop7 { get; set; }
    
        [JsonIgnore]
        public string Prop8 { get; set; }
    
        [JsonIgnore]
        public string Prop9 { get; set; }
    
        [JsonIgnore]
        public string Prop10 { get; set; }
    }
    

    参考 How to ignore properties with System.Text.Json