惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

博客园_首页
Y
Y Combinator Blog
Engineering at Meta
Engineering at Meta
D
Docker
GbyAI
GbyAI
aimingoo的专栏
aimingoo的专栏
大猫的无限游戏
大猫的无限游戏
腾讯CDC
P
Proofpoint News Feed
A
About on SuperTechFans
WordPress大学
WordPress大学
Stack Overflow Blog
Stack Overflow Blog
Google DeepMind News
Google DeepMind News
C
Check Point Blog
Microsoft Security Blog
Microsoft Security Blog
H
Hackread – Cybersecurity News, Data Breaches, AI and More
L
LangChain Blog
MyScale Blog
MyScale Blog
博客园 - 三生石上(FineUI控件)
Hugging Face - Blog
Hugging Face - Blog
Microsoft Azure Blog
Microsoft Azure Blog
N
Netflix TechBlog - Medium
G
Google Developers Blog
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻

博客园 - On the road....

c# -- 对象销毁和垃圾回收 C#集合 -- Equality和Order插件 C#集合--Dictionary C#集合 -- 自定义集合与代理 C#集合 -- Lists,Queues, Stacks 和 Sets C#集合--ICollection接口和IList接口 C#集合--数组 C#集合-列举(Enumeration) C#排序比较 Customer IEnuramble Extension C#相等性比较 c#列举和迭代器 C#记录对象的变化 c#如何区分静态只读变量和常量 C#如何更好地理解引用类型和值类型 C#代理那点事儿 Pro ASP.NET MVC –第五章 使用Razor Pro ASP.NET MVC –第六章 MVC的基本工具 Pro ASP.NET MVC –第四章 语言特性精华
C#按需序列化对象为Json字符串
On the road.... · 2014-02-21 · via 博客园 - On the road....

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

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

收工,走人

posted @ 2014-02-21 16:56  On the road....  阅读(1549)  评论()    收藏  举报