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(
'\"');
        }

    }

}

posted on 2007-09-06 22:35 黄尚 阅读( ...) 评论( ...) 编辑 收藏

转载于:https://www.cnblogs.com/afxcn/archive/2007/09/06/884950.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值