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(); } }
收工,走人
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。