0

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

//json string output
{ IdNumber: "001254810", Name: "", Email: "" }
4
  • What is your question? Commented Jun 23, 2015 at 13:20
  • How can I implement a custom serializer using JSON.NET to call the ToString method for the specific properties (the CDataFields)? Commented Jun 23, 2015 at 13:25
  • I don't see any effort of implementing a custom converter. Have you tried it? Commented Jun 23, 2015 at 13:28
  • Yes @YuvalItzchakov, I tried using the approach David suggested. The problem with that way is WriteJson method gets call for every property, but inside the object I want to serialize I have other complex object and I don't want to write logic for those because they serialize fine. Commented Jun 23, 2015 at 13:45

2 Answers 2

0

Look at this answer, it might help you Custom Json Serialization of class

or here http://blog.maskalik.com/asp-net/json-net-implement-custom-serialization/

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.