2015-06-23 77 views
0

我正在使用newtonsoft JSON.NET庫來序列化我無法修改的第三方庫的對象。該對象的某些屬性序列化爲空字符串,儘管它們有價值。所以我想調用ToString來獲取並序列化僅用於特定類型屬性的值。從第三方庫類(newtonsoft)實現自定義Json序列化程序

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 = "[email protected]" 
}; 
var jsonstring = Newtonsoft.Json.JsonConvert.SerializeObject(transactionModel) 

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

你的問題是什麼? –

+0

如何使用JSON.NET實現自定義序列化程序以調用特定屬性(CDataFields)的ToString方法? –

+0

我看不到任何實現自定義轉換器的努力。你試過了嗎? –

回答

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 = "[email protected]" 
    } 
); 
相關問題