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

时间:2021-01-16 15:27:14

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

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

实体类

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

测试代码

class Program
{
static void Main(string[] args)
{
Staff s = new Staff("", "", "");
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

收工,走人