简体   繁体   中英

Implement custom Json serializer for properties from thrid party library class (newtonsoft)

I'm using newtonsoft JSON.NET library to serialize a object of a thrid party library which I can't modify. Some of the properties of this object serialize to an empty string although they have value. So I want to call the ToString to get and serialize the value only for the properties that are of certain type.

namespace ThirdParty.Lib
{
    public class Info 
    {
       // When newtonsoft serialize a property of this type (CDataField) 
       // a get an empty string as value.
       public CDataField Name { get; set; }
       public CDataField Email { get; set; }
       public string IdNNumber {get; set;}
    }
}

var info = new ThirdParty.Lib.Info
{
   IdNumber = "001254810",
   Name = "John Doe",
   Email = "johndoe@gmail.com"
};
var jsonstring = Newtonsoft.Json.JsonConvert.SerializeObject(transactionModel)

//json string output
{ IdNumber: "001254810", Name: "", Email: "" }

The simplest way is to implement a "cloned" class and serialize that. Like:

namespace MyNameSpace
{
    public class Info 
    {
        // When newtonsoft serialize a property of this type (CDataField) 
        // a get an empty string as value.
        public string Name { get; set; }
        public string Email { get; set; }
        public string IdNNumber {get; set;}

        Info(ThirdiParty.Lib.Info info)
        {
            Name = info.Name.ToString();
            Email = info.Email.ToString();
            IdNumber = info.IdNumber;
        }
    }
 }

var myinfo = new MyNameSpace.Info(
    new ThirdiParty.Lib.Info()
    {
        IdNumber = "001254810",
        Name = "John Doe",
        Email = "johndoe@gmail.com"
    }
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM