Home > Software design >  How can I ignore the property name that I use in the jsonproperty attribute, provided that it is onl
How can I ignore the property name that I use in the jsonproperty attribute, provided that it is onl

Time:07-15

My problem is that I deserialize the incoming data and transfer it to this class using jsonproperty. but I don't want to use property name attribute that I use in jsonproperty while serializing.

example class

public class DocumentDetail
    {
        [JsonProperty("KAREKOD")]
        public string qrCode { get; set; }
        [JsonProperty("GTIN")]
        public string gtinNumber { get; set; }
        [JsonProperty("LOTNUMBER")]
        public string lotNumber { get; set; }
    }

example serialize

{
  DocumentDetail docDetail=new DocumentDetail(){qrCode="123456adsfg789",gtinNumber ="123asdf548654",lotNumber ="1231231sdfg23"};
  var obj=JsonConvert.SerializeObject(body);
}

example result

{
    "qrCode" : "123456adsfg789",
    "gtinNumber" : "123asdf548654",
    "lotNumber" : "1231231sdfg23"
}

CodePudding user response:

you can add a constructor to your class

public class DocumentDetail
{
    public string qrCode { get; set; }

    public string gtinNumber { get; set; }

    [JsonProperty("lotNumber")] // optional, you can assign any name for serialization
    public string lotNumber { get; set; }
    
    [Newtonsoft.Json.JsonConstructor]
    public  DocumentDetail( string KAREKOD,string GTIN, string LOTNUMBER)
    {
        qrCode=KAREKOD;
        gtinNumber=GTIN;
        lotNumber=LOTNUMBER;
    }
    public DocumentDetail() {}
}

and you don't need to include all properties in the constructor, just include the properties that need different names for a serialization and a deserialiazation.

  • Related