JsonConvert.SerializeObject(本);在JSON中呈现函数的结果

时间:2013-02-28 15:04:55

标签: c# json

有没有办法让JsonConvert.SerializeObject(this);在类中呈现函数的结果?

     public string Name { get; private set; } // renders fine in the outputted json



        public string AdHocRecipientsStub()// I want this also in the outputted json
            {
                return AdHocRecipients.ToString().Substring(0, 15) + "...";
            }

1 个答案:

答案 0 :(得分:2)

您可以将其包装在属性中:

static void Main(string[] args)
{
    Console.WriteLine(JsonConvert.SerializeObject(new Test()));
}

public class Test
{
    public string Test1 { get { return "test1"; } }
    public string Test2 { get { return Test2Func(); } }
    private string Test2Func()
    {
        return "test2";
    }
}

输出:

{"Test1":"test1","Test2":"test2"}