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); } }
实体类
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; } }
测试代码
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(); } }
收工,走人