PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, July 24, 2022

[FIXED] How can I ignore the property name that I use in the jsonproperty attribute, provided that it is only once

 July 24, 2022     .net, c#, json, json.net     No comments   

Issue

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"
}

Solution

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.



Answered By - Serge
Answer Checked By - Gilberto Lyons (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing