zoukankan      html  css  js  c++  java
  • 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

    实体类

    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("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

    收工,走人

  • 相关阅读:
    git知识点总结
    自动化进阶
    unittest单元测试框架
    自动化测试模型
    webdriver
    python文件处理
    uva 11077 置换
    poj 1066 Treasure Hunt
    poj 2661 Factstone Benchmark
    hdu 4180
  • 原文地址:https://www.cnblogs.com/yang_sy/p/3559779.html
Copyright © 2011-2022 走看看