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

推荐订阅源

G
Google Developers Blog
Google DeepMind News
Google DeepMind News
Hugging Face - Blog
Hugging Face - Blog
D
Docker
F
Fortinet All Blogs
博客园 - 三生石上(FineUI控件)
Project Zero
Project Zero
Engineering at Meta
Engineering at Meta
J
Java Code Geeks
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
Simon Willison's Weblog
Simon Willison's Weblog
S
Security Affairs
NISL@THU
NISL@THU
T
Tor Project blog
A
About on SuperTechFans
宝玉的分享
宝玉的分享
腾讯CDC
S
Schneier on Security
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
P
Privacy & Cybersecurity Law Blog
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
Stack Overflow Blog
Stack Overflow Blog
P
Privacy International News Feed
雷峰网
雷峰网
C
Cyber Attacks, Cyber Crime and Cyber Security
Vercel News
Vercel News
Cisco Talos Blog
Cisco Talos Blog
D
DataBreaches.Net
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
Google Online Security Blog
Google Online Security Blog
Recorded Future
Recorded Future
L
LINUX DO - 热门话题
Microsoft Security Blog
Microsoft Security Blog
Latest news
Latest news
C
Check Point Blog
有赞技术团队
有赞技术团队
T
The Exploit Database - CXSecurity.com
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
云风的 BLOG
云风的 BLOG
SecWiki News
SecWiki News
Application and Cybersecurity Blog
Application and Cybersecurity Blog
爱范儿
爱范儿
月光博客
月光博客
V
Vulnerabilities – Threatpost
T
Threat Research - Cisco Blogs
P
Palo Alto Networks Blog
T
The Blog of Author Tim Ferriss
C
Cisco Blogs
Webroot Blog
Webroot Blog
S
Security @ Cisco Blogs

博客园 - 张远强

原版SQLHelper.cs下载 Chrome浏览器Proxy Switchy、Tampermonkey等扩展程序下载 GreaseMonkey脚本:阻止Google转换搜索链接地址 站在31岁,理解程序员年过三十这道坎 GreaseMonkey让网站登录验证码形同虚设 DateTime.ToString格式限定符转义 借Windows说明Linux分区和挂载点 彻底解决ASP.NET MD5加密中文结果和ASP不一致的问题 SharpZipLib使用示例 DotNetZip使用示例 Dvbbs 8.2.0 RC1多功能编辑器,提供下载 B/S系统版本管理V1.0正式发布 ASP.NET 2.0缓存 个人网站与动网整合步骤(支持PDO1.0) - 张远强 - 博客园 C#中显/隐式实现接口及其访问方法 C#接口范例 巧用escape解决ASP.NET中URL传参乱码问题 使用Filter实现信息的二次检索 使用overflow代替left截取指定长度字符串
JSON解析类(C#)
张远强 · 2010-01-06 · via 博客园 - 张远强

使用本文中的JSONConvert类可将任意JSON字符串转化为JSONObject或JSONArray对象,并获取需要的值,克服了.NET自带JSON类反序列化时需知道并引用序列化时使用的类的缺点。当然,也可以使用JSONConvert类进行序列化,构造出JSON字符串。

JSON解析类

//using System.Collections.Generic;
//using System.Text;
//using System.Text.RegularExpressions;

/// <summary>
/// 类  名:JSONConvert
/// 描  述:JSON解析类
/// 编  写:dnawo
/// 站  点:http://www.mzwu.com/
/// 日  期:2010-01-06
/// 版  本:1.1.0
/// </summary>
public static class JSONConvert
{
    
#region 全局变量private static JSONObject _json = new JSONObject();//寄存器
    private static readonly string _SEMICOLON = "@semicolon";//分号转义符
    private static readonly string _COMMA = "@comma"//逗号转义符

    
#endregion#region 字符串转义
    
/// <summary>
    
/// 字符串转义,将双引号内的:和,分别转成_SEMICOLON和_COMMA
    
/// </summary>
    
/// <param name="text"></param>
    
/// <returns></returns>
    private static string StrEncode(string text)
    {
        MatchCollection matches 
= Regex.Matches(text, "\\\"[^\\\"]+\\\"");
        foreach (Match match in matches)
        {
            text 
= text.Replace(match.Value, match.Value.Replace(":", _SEMICOLON).Replace(",", _COMMA));
        }
return text;
    }
/// <summary>
    
/// 字符串转义,将_SEMICOLON和_COMMA分别转成:和,
    
/// </summary>
    
/// <param name="text"></param>
    
/// <returns></returns>
    private static string StrDecode(string text)
    {
        
return text.Replace(_SEMICOLON, ":").Replace(_COMMA, ",");
    }
#endregion#region JSON最小单元解析/// <summary>
    
/// 最小对象转为JSONObject
    
/// </summary>
    
/// <param name="text"></param>
    
/// <returns></returns>
    private static JSONObject DeserializeSingletonObject(string text)
    {
        JSONObject jsonObject 
= new JSONObject();

        MatchCollection matches 

= Regex.Matches(text, "(\\\"(?<key>[^\\\"]+)\\\":\\\"(?<value>[^,\\\"]+)\\\")|(\\\"(?<key>[^\\\"]+)\\\":(?<value>[^,\\\"\\}]+))");
        
foreach (Match match in matches)
        {
            
string value = match.Groups["value"].Value;
            jsonObject.Add(match.Groups[
"key"].Value, _json.ContainsKey(value) ? _json[value] : StrDecode(value));
        }
return jsonObject;
    }
/// <summary>
    
/// 最小数组转为JSONArray
    
/// </summary>
    
/// <param name="text"></param>
    
/// <returns></returns>
    private static JSONArray DeserializeSingletonArray(string text)
    {
        JSONArray jsonArray 
= new JSONArray();

        MatchCollection matches 

= Regex.Matches(text, "(\\\"(?<value>[^,\\\"]+)\")|(?<value>[^,\\[\\]]+)");
        foreach (Match match in matches)
        {
            
string value = match.Groups["value"].Value;
            jsonArray.Add(_json.ContainsKey(value) 
? _json[value] : StrDecode(value));
        }
return jsonArray;
    }
/// <summary>
    
/// 反序列化
    
/// </summary>
    
/// <param name="text"></param>
    
/// <returns></returns>
    private static string Deserialize(string text)
    {
        text 
= StrEncode(text);//转义;和,

        
int count = 0;
        
string key = string.Empty;
        
string pattern = "(\\{[^\\[\\]\\{\\}]+\\})|(\\[[^\\[\\]\\{\\}]+\\])";while (Regex.IsMatch(text, pattern))
        {
            MatchCollection matches 
= Regex.Matches(text, pattern);
            
foreach (Match match in matches)
            {
                key 
= "___key" + count + "___";if (match.Value.Substring(01== "{")
                    _json.Add(key, DeserializeSingletonObject(match.Value));
                
else
                    _json.Add(key, DeserializeSingletonArray(match.Value));

                text 

= text.Replace(match.Value, key);

                count

++;
            }
        }
        
return text;
    }
#endregion#region 公共接口/// <summary>
    
/// 序列化JSONObject对象
    
/// </summary>
    
/// <param name="text"></param>
    
/// <returns></returns>
    public static JSONObject DeserializeObject(string text)
    {
        
return _json[Deserialize(text)] as JSONObject;
    }
/// <summary>
    
/// 序列化JSONArray对象
    
/// </summary>
    
/// <param name="text"></param>
    
/// <returns></returns>
    public static JSONArray DeserializeArray(string text)
    {
        
return _json[Deserialize(text)] as JSONArray;
    }
    
    
/// <summary>
    
/// 反序列化JSONObject对象
    
/// </summary>
    
/// <param name="jsonObject"></param>
    
/// <returns></returns>
    public static string SerializeObject(JSONObject jsonObject)
    {
        StringBuilder sb 
= new StringBuilder();
        sb.Append(
"{");
        
foreach (KeyValuePair<stringobject> kvp in jsonObject)
        {
            
if (kvp.Value is JSONObject)
            {
                sb.Append(
string.Format("\"{0}\":{1},", kvp.Key, SerializeObject((JSONObject)kvp.Value)));
            }
            
else if (kvp.Value is JSONArray)
            {
                sb.Append(
string.Format("\"{0}\":{1},", kvp.Key, SerializeArray((JSONArray)kvp.Value)));
            }
            
else if (kvp.Value is String)
            {
                sb.Append(
string.Format("\"{0}\":\"{1}\",", kvp.Key, kvp.Value));
            }
            
else
            {
                sb.Append(
string.Format("\"{0}\":\"{1}\",", kvp.Key, ""));
            }
        }
        
if (sb.Length > 1)
            sb.Remove(sb.Length 
- 11);
        sb.Append(
"}");
        
return sb.ToString();
    }
    
    
/// <summary>
    
/// 反序列化JSONArray对象
    
/// </summary>
    
/// <param name="jsonArray"></param>
    
/// <returns></returns>
    public static string SerializeArray(JSONArray jsonArray)
    {
        StringBuilder sb 
= new StringBuilder();
        sb.Append(
"[");
        
for (int i = 0; i < jsonArray.Count; i++)
        {
            
if (jsonArray[i] is JSONObject)
            {
                sb.Append(
string.Format("{0},", SerializeObject((JSONObject)jsonArray[i])));
            }
            
else if (jsonArray[i] is JSONArray)
            {
                sb.Append(
string.Format("{0},", SerializeArray((JSONArray)jsonArray[i])));
            }
            
else if (jsonArray[i] is String)
            {
                sb.Append(
string.Format("\"{0}\",", jsonArray[i]));
            }
            
else
            {
                sb.Append(
string.Format("\"{0}\","""));
            }

        }

if (sb.Length > 1)
            sb.Remove(sb.Length 
- 11);
        sb.Append(
"]");
        
return sb.ToString();
    }
    
#endregion
}
/// <summary>
/// 类  名:JSONObject
/// 描  述:JSON对象类
/// 编  写:dnawo
/// 站  点:http://www.mzwu.com/
/// 日  期:2010-01-06
/// 版  本:1.1.0
/// 更新历史:
///     2010-01-06  继承Dictionary<TKey, TValue>代替this[]
/// </summary>
public class JSONObject : Dictionary<stringobject>
{}
/// <summary>
/// 类  名:JSONArray
/// 描  述:JSON数组类
/// 编  写:dnawo
/// 站  点:http://www.mzwu.com/
/// 日  期:2010-01-06
/// 版  本:1.1.0
/// 更新历史:
///     2010-01-06  继承List<T>代替this[]
/// </summary>
public class JSONArray : List<object>
{}

调用示例

调用示例

//序列化
JSONArray jsonArray = new JSONArray();
jsonArray.Add(
"2006");
jsonArray.Add(
"2007");
jsonArray.Add(
"2008");
jsonArray.Add(
"2009");
jsonArray.Add(
"2010");

JSONObject jsonObject 

= new JSONObject();
jsonObject.Add(
"domain""mzwu.com");
jsonObject.Add(
"years", jsonArray);

Console.WriteLine(JSONConvert.SerializeObject(jsonObject));

//反序列化
JSONObject json = JSONConvert.DeserializeObject("{\"domain\":\"mzwu.com\",\"years\":[2006,2007,2008,2009,2010]}");
if (json != null)
{
    Console.WriteLine(json[
"domain"]);
    Console.WriteLine(((JSONArray)json[
"years"])[3]);
}