zoukankan      html  css  js  c++  java
  • JSONSerializer把类转换成JSON字符串

    阅读优秀的代码真的是种享受,从ProMesh的项目中发现了现在的一段优美的代码,记下来,也让喜欢它的人有机会阅读到.

    //=============================================================================
    // ProMesh.NET - .NET Web Application Framework 
    //
    // Copyright (c) 2003-2007 Philippe Leybaert
    //
    // Permission is hereby granted, free of charge, to any person obtaining a copy 
    // of this software and associated documentation files (the "Software"), to deal 
    // in the Software without restriction, including without limitation the rights 
    // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
    // copies of the Software, and to permit persons to whom the Software is 
    // furnished to do so, subject to the following conditions:
    //
    // The above copyright notice and this permission notice shall be included in 
    // all copies or substantial portions of the Software.
    // 
    // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
    // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
    // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
    // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
    // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 
    // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
    // IN THE SOFTWARE.
    //=============================================================================

    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.Globalization;
    using System.Reflection;
    using System.Text;

    namespace Activa.ProMesh
    {
        
    public class JSONSerializer
        
    {
            
    private readonly StringBuilder _output = new StringBuilder();

            
    public static string ToJSON(object obj)
            
    {
                
    return new JSONSerializer().ConvertToJSON(obj);
            }


            
    private string ConvertToJSON(object obj)
            
    {
                WriteValue(obj);

                
    return _output.ToString();
            }


            
    private void WriteValue(object obj)
            
    {
                
    if (obj == null)
                    _output.Append(
    "null");
                
    else if (obj is sbyte || obj is byte || obj is short || obj is ushort || obj is int || obj is uint || obj is long || obj is ulong || obj is decimal || obj is double || obj is float)
                    _output.Append(Convert.ToString(obj,NumberFormatInfo.InvariantInfo));
                
    else if (obj is bool)
                    _output.Append(obj.ToString().ToLower());
                
    else if (obj is char || obj is Enum || obj is Guid)
                    WriteString(
    "" + obj);
                
    else if (obj is DateTime)
                    _output.Append(
    "new Date(" + ((DateTime)obj - new DateTime(1970,1,1)).TotalMilliseconds.ToString("0"+ ")");
                
    else if (obj is string)
                    WriteString((
    string)obj);
                
    else if (obj is IDictionary)
                    WriteDictionary((IDictionary)obj);
                
    else if (obj is Array || obj is IList || obj is ICollection)
                    WriteArray((IEnumerable)obj);
                
    else
                    WriteObject(obj);
            }


            
    private void WriteObject(object obj)
            
    {
                _output.Append(
    "");

                
    bool pendingSeparator = false;

                
    foreach (FieldInfo field in obj.GetType().GetFields(BindingFlags.Public|BindingFlags.Instance))
                
    {
                    
    if (pendingSeparator)
                        _output.Append(
    " , ");

                    WritePair(field.Name, field.GetValue(obj));

                    pendingSeparator 
    = true;
                }


                
    foreach (PropertyInfo property in obj.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance))
                
    {
                    
    if (!property.CanRead)
                        
    continue;

                    
    if (pendingSeparator)
                        _output.Append(
    " , ");

                    WritePair(property.Name,property.GetValue(obj, 
    null));

                    pendingSeparator 
    = true;
                }


                _output.Append(
    " }");
            }


            
    private void WritePair(string name, object value)
            
    {
                WriteString(name);

                _output.Append(
    " : ");

                WriteValue(value);
            }


            
    private void WriteArray(IEnumerable array)
            
    {
                _output.Append(
    "");

                
    bool pendingSeperator = false;

                
    foreach (object obj in array)
                
    {
                    
    if (pendingSeperator)
                        _output.Append(
    ',');

                    WriteValue(obj);

                    pendingSeperator 
    = true;
                }


                _output.Append(
    " ]");
            }


            
    private void WriteDictionary(IDictionary dic)
            
    {
                _output.Append(
    "");

                
    bool pendingSeparator = false;

                
    foreach (DictionaryEntry entry in dic)
                
    {
                    
    if (pendingSeparator)
                        _output.Append(
    " , ");

                    WritePair(entry.Key.ToString(),entry.Value);

                    pendingSeparator 
    = true;
                }


                _output.Append(
    " }");
            }


            
    private void WriteString(string s)
            
    {
                _output.Append(
    '\"');

                
    foreach (char c in s)
                
    {
                    
    switch (c)
                    
    {
                        
    case '\t': _output.Append("\\t"); break;
                        
    case '\r': _output.Append("\\r"); break;
                        
    case '\n': _output.Append("\\n"); break;
                        
    case '"'
                        
    case '\\': _output.Append("\\" + c); break;
                        
    default:
                            
    {
                                
    if (c >= ' ' && c < 128)
                                    _output.Append(c);
                                
    else
                                    _output.Append(
    "\\u" + ((int) c).ToString("X4"));
                            }

                            
    break;
                    }

                }


                _output.Append(
    '\"');
            }

        }

    }

  • 相关阅读:
    [Azure][PowerShell][ASM][03]Cloud Service
    linux ssh连接自动断开问题
    NTP服务器实现
    xshell使用小技巧
    elasticsearch集群部署
    redis集群部署
    积分排名查看
    linux centos7.2系统升级python后yum不能使用的问题
    Python生成器generator之next和send运行流程
    python文件操作
  • 原文地址:https://www.cnblogs.com/afxcn/p/884950.html
Copyright © 2011-2022 走看看