我使用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: "" }
答案 0 :(得分:0)
看看这个答案,它可能会帮助你Custom Json Serialization of class
或在这里 http://blog.maskalik.com/asp-net/json-net-implement-custom-serialization/
答案 1 :(得分:0)
最简单的方法是实现“克隆”类并对其进行序列化。像:
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"
}
);