C#按需序列化对象为Json字符串

只贴代码,不解释了。新的代理类型确实很给力!

C#按需序列化对象为Json字符串
public static class JsonHelper
{
    public static string ToJsonString<T>(IList<T> list, Func<T, string> fun)
    {
        StringBuilder buffer = new StringBuilder();
        bool isFirst = true;            
        
        foreach (T t in list)
        {
            if (!isFirst)
                buffer.Append(",");

            buffer.Append(fun(t));
            isFirst = false;
        }

        return buffer.ToString();
    }      

    public static string ToJsonString<T>(T t, Func<T, string> fun)
    {
        return fun(t);
    }
}
Josn Helper

实体类

C#按需序列化对象为Json字符串
public class Staff
{
    public string StaffNo { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }

    public Staff(string no, string fn, string ln)
    {
        StaffNo = no;
        FirstName = fn;
        LastName = ln;
    }
}
Staff Class

测试代码

C#按需序列化对象为Json字符串
class Program
{
    static void Main(string[] args)
    {
        Staff s = new Staff("10000", "11111", "22222");
        IList<Staff> list = new List<Staff> { s,s };          

        JsonHelper.ToJsonString<Staff>(list, o=>string.Format("{{firstname:{0}}}", o.FirstName));
        JsonHelper.ToJsonString<Staff>(s, o=>string.Format("{{firstname:{0}, lastname:{1}}}", o.FirstName, o.LastName)); 
        
        Console.ReadLine();
    }
}
Test code

 

收工,走人

C#按需序列化对象为Json字符串

上一篇:Silverlight 后台利用代码触发 Button 的Click事件


下一篇:HtmlTextWriter学习笔记