为第三方库类(newtonsoft)中的属性实现自定义Json序列化程序



我使用的是newtonsoft JSON。NET库来序列化我无法修改的第三方库的对象。该对象的某些属性序列化为空字符串,尽管它们具有值。因此,我想调用ToString来获取并序列化仅针对特定类型的属性的值。

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

看看这个答案,它可能会帮助您自定义类的Json序列化

或者在这里http://blog.maskalik.com/asp-net/json-net-implement-custom-serialization/

最简单的方法是实现一个"克隆的"类并序列化它。类似:

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

相关内容

  • 没有找到相关文章

最新更新