C#字符串数组排序 C#排序算法大全 C#字符串比较方法 一个.NET通用JSON解析/构建类的实现(c#) C#处理Json文件 asp.net使用Jquery+iframe传值问题

时间:2020-12-25 04:58:54

C#字符串数组排序

 
//排序只带字符的数组,不带数字的
private   string[]   aa   ={ "a ", "c ", "b "};
Array.Sort(aa);
    MessageBox.Show(aa[0]);
    MessageBox.Show(aa[1]);
    MessageBox.Show(aa[2]);
 
结果是:a,b,c

如果想实现

Array.Sort(arr); 
不对!!!!!!!!!! 
比如:   A1,A2,A10 
用Array.Sort(arr);排出来就是 
A1,A10,A2 
而我要的是 
A1,A2,A10

这样就可以了:
public   class   CustomComparer:System.Collections.IComparer
{
public   int   Compare(object   x,   object   y){
string   s1   =   (string)x;
string   s2   =   (string)y;
if   (s1.Length   >   s2.Length)   return   1;
if   (s1.Length   <   s2.Length)   return   -1;
for   (int   i   =   0;   i   <   s1.Length;   i++)   {
if   (s1[i]   >   s2[i])   return   1;
if   (s1[i]   <   s2[i])   return   -1;
}
return   0;
}
}
 
应用:
string[]   str   =   new   string[]{ "A1 ", "A2 ", "A10 "};
Array.Sort(str,   new   CustomComparer());
for   (int   i   =   0;   i   <   str.Length;   i++)
Console.WriteLine(str[i]);

但是这样不对带有字符的字符排序。

C#排序算法大全

 
C#排序算法大全
土人
2004-7-21
一、冒泡排序(Bubble)
 
using System;
 
namespace BubbleSorter
{
public class BubbleSorter
{
public void Sort(int[] list)
{
int i,j,temp;
bool done=false;
j=1;
while((j<list.Length)&&(!done))
{
done=true;
for(i=0;i<list.Length-j;i++)
{
if(list[i]>list[i+1])
{
done=false;
temp=list[i];
list[i]=list[i+1];
list[i+1]=temp;
}
}
j++;
}
}
}
 
public class MainClass
{
public static void Main()
{
int[] iArrary=new int[]{1,5,13,6,10,55,99,2,87,12,34,75,33,47};
BubbleSorter sh=new BubbleSorter();
sh.Sort(iArrary);
for(int m=0;m<iArrary.Length;m++)
Console.Write("{0} ",iArrary[m]);
Console.WriteLine();
}
}
}
 
二、选择排序(Selection)
 
using System;
 
namespace SelectionSorter
{
public class SelectionSorter
{
private int min;
public void Sort(int [] list)
{
for(int i=0;i<list.Length-1;i++)
{
min=i;
for(int j=i+1;j<list.Length;j++)
{
if(list[j]<list[min])
min=j;
}
int t=list[min];
list[min]=list[i];
list[i]=t;
}
}
}
 
public class MainClass
{
public static void Main()
{
int[] iArrary = new int[]{1,5,3,6,10,55,9,2,87,12,34,75,33,47};
SelectionSorter ss=new SelectionSorter();
ss.Sort(iArrary);
for (int m=0;m<iArrary.Length;m++)
Console.Write("{0} ",iArrary[m]);
Console.WriteLine();
}
}
}
 
三、插入排序(InsertionSorter)
 
using System;
 
namespace InsertionSorter
{
public class InsertionSorter
{
public void Sort(int [] list)
{
for(int i=1;i<list.Length;i++)
{
int t=list[i];
int j=i;
while((j>0)&&(list[j-1]>t))
{
list[j]=list[j-1];
--j;
}
list[j]=t;
}
}
}
 
public class MainClass
{
public static void Main()
{
int[] iArrary=new int[]{1,13,3,6,10,55,98,2,87,12,34,75,33,47};
InsertionSorter ii=new InsertionSorter();
ii.Sort(iArrary);
for(int m=0;m<iArrary.Length;m++)
Console.Write("{0}",iArrary[m]);
Console.WriteLine();
}
}
}
 
四、希尔排序(ShellSorter)
 
using System;
 
namespace ShellSorter
{
public class ShellSorter
{
public void Sort(int [] list)
{
int inc;
for(inc=1;inc<=list.Length/9;inc=3*inc+1);
for(;inc>0;inc/=3)
{
for(int i=inc+1;i<=list.Length;i+=inc)
{
int t=list[i-1];
int j=i;
while((j>inc)&&(list[j-inc-1]>t))
{
list[j-1]=list[j-inc-1];
j-=inc;
}
list[j-1]=t;
}
}
}
}
 
public class MainClass
{
public static void Main()
{
int[] iArrary=new int[]{1,5,13,6,10,55,99,2,87,12,34,75,33,47};
ShellSorter sh=new ShellSorter();
sh.Sort(iArrary);
for(int m=0;m<iArrary.Length;m++)
Console.Write("{0} ",iArrary[m]);
Console.WriteLine();
}
}
}

C#字符串比较方法

 
 

用C#比较字符串有多种方法,如:

1. string.Compare(x,y);
2. string.Equals(x,y) ;

如果要不区分大小写进行比较,则对应为:
string.Compare(x,y);
string.Equals(x,y);

注:string.Compare比较结果的含义:

含义

小于零

x 小于 y。 或 x 为 空引用(在 Visual Basic 中为 Nothing)。

x 等于 y。

大于零

x 大于 y。 或 y 为 空引用(在 Visual Basic 中为 Nothing)。

string.Equals比较结果的含义为:

含义

true

x 等于 y。

false

x 不等 y。


其它常用字符串操作:

1、从字符串中提取子串
StringBuilder 类没有支持子串的方法,因此必须用String类来提取。
string mystring="My name is ynn.";
//Displays "name is ynn."
Console.WriteLine(mystring.Substring( 3 ));
//Displays "ynn"
Console.WriteLine(mystring.Substring( 11,3 ));

2、比较字符串
String 类有四种方法:Compare( )、CompareTo( )、CompareOrdinal( )、Equals( )。
Compare( )方法是CompareTo( )方法的静态版本。只要使用“=”运算符,就会调用Equals( )方法,的以Equals( )方法与“=”是等价的。CompareOrdinal( )方法对两个字符串比较不考本地语言与文件。
示例:
int result;
bool bresult;
s1="aaaa";
s2="bbbb";
//Compare( )method
//result值为“0”表示等,小于零表示 s1 < s2,大于零表示 s1 > s2
result=String.Compare(s1,s2);
result=s1.CompareTo( s2 );
result=String.CompareOrdinal(s1,s2);
bresult=s1.Equals( s2 );
bresult=String.Equals( s1,s2 );
一个例外情况是,两个字符串都是内置的,并相等,静态方法要快得多。

3、字符串格式化

3.1 格式化数字
格式字符    说明和关联属性


c、C       货币格式。
d、D       十进制格式。 
e、E       科学计数(指数)格式。 
f、F       固定点格式。 
g、G       常规格式。 
n、N       数字格式。 
r、R       往返格式,确保将已转换成字符串的数字转换回数字时具有与原数字相同的值。 
x、X       十六进制格式。


double val=Math.PI;
Console.WriteLine(val.ToString( ));  //displays 3.14159265358979
Console.WriteLine(val.ToString("E"));//displays 3.141593E+000
Console.WriteLine(val.ToString("F3");//displays 3.142
int val=65535;
Console.WriteLine(val.ToString("x"));  //displays ffff
Console.WriteLine(val.ToString("X"));  //displays FFFF
Single val=0.123F;
Console.WriteLine(val.ToString("p"));  //displays 12.30 %
Console.WriteLine(val.ToString("p1"));  //displays 12.3 %
默认格式化会在数字和百分号之间放入一个空格。定制方法如下: 
其中NumberFormatInfo类是System.Globalization命名空间的一个成员,因此该命名空间必须导入到程序中。
Single val=0.123F;
object myobj=NumberFormatInfo.CurrentInfo.Clone( ) as NumberFormatInfo;
NumberFormatInfo myformat=myobj as NumberFormatInfo;
myformat.PercentPositivePattern=1;
Console.WriteLine(val.ToString("p",myformat)); //displays 12.30%;
Console.WriteLine(val.ToString("p1",myformat)); //displays 12.3%;
格式化具有很大的灵活性。下面的例子演示一个没有意义的货币结构:
double val=1234567.89;
int [] groupsize={2,1,3};
object myobj=NumberFormatInfo.CurrentInfo.Clone( );
NumberFormatInfo mycurrency=myobj as NumberFormatInfo;
mycurrency.CurrencySymbol="#"; //符号
mycurrency.CurrencyDecimalSeparator=":"; //小数点
mycurrency.CurrencyGroupSeparator="_";  //分隔符
mycurrency.CurrencyGroupSizes=groupsize;
// 输出 #1_234_5_67:89
Console.WriteLine(val.ToString("C",mycurrency));

3.2 格式化日期
输出形式取决于用户计算机的文化设置。
using System;
using System.Globalization; 
public class MainClass 

  public static void Main(string[] args)  
  {
        DateTime dt = DateTime.Now;
        String[] format = {"d","D","f","F","g","G","m","r","s","t", "T","u", "U","y","dddd, MMMM dd yyyy","ddd, MMM d \"'\"yy","dddd, MMMM dd","M/yy","dd-MM-yy",};
        String date;
      for (int i = 0; i < format.Length; i++) 
      {
         date = dt.ToString(format[i], DateTimeFormatInfo.InvariantInfo);
         Console.WriteLine(String.Concat(format[i], " :" , date));
      }
     }
}
d :07/11/2004    <=======输出
D :Sunday, 11 July 2004
f :Sunday, 11 July 2004 10:52
F :Sunday, 11 July 2004 10:52:36
g :07/11/2004 10:52
G :07/11/2004 10:52:36
m :July 11
r :Sun, 11 Jul 2004 10:52:36 GMT
s :2004-07-11T10:52:36
t :10:52
T :10:52:36
u :2004-07-11 10:52:36Z
U :Sunday, 11 July 2004 02:52:36
y :2004 July
dddd, MMMM dd yyyy :Sunday, July 11 2004
ddd, MMM d "'"yy :Sun, Jul 11 '04
dddd, MMMM dd :Sunday, July 11
M/yy :7/04
dd-MM-yy :11-07-04

3.3 格式化枚举
enum classmen
{
  ynn=1,
  yly=2,
  css=3,
  C++=4
}
获取枚举字符串信息如下:
classmen myclassmen=classmen.yly;
Console.WriteLine(myclassmen.ToString( ));   //displays yly
Console.WriteLine(myclassmen.ToString("d")); //displays 2
从系统枚举中获取文本人信息如下:
DayOfWeek day=DayOfWeek.Friday;
//displays "Day is Friday"
Console.WriteLine(String.Format("Day is {0:G}",day));
格式化字符串“ G ”把枚举显示为一个字符串。

一个.NET通用JSON解析/构建类的实现(c#)

 
 

在.NET Framework 3.5中已经提供了一个JSON对象的序列化工具,但是他是强类型的,必须先按JSON对象的格式定义一个类型,并将类型加上JSON序列化特性。本文将试图提供一个高度灵活的JSON通用类型(JsonObject),实现对JSON的解析及序列化。

假设JSON对象内容如下:

隐藏行号 复制代码 ? JSON
  1. {
  2. orders: {
  3. date: '21:31:59',
  4. name: 'Xfrog',
  5. books: [{
  6. name: 'C# 网络核心编程',
  7. publish: '2010-3-24'
  8. }, {
  9. name: 'C#入门经典中文版',
  10. publish: '2009-10-16'
  11. }]
  12.     },
  13. blog: 'http://www.cnblogs.com/xfrog'
  14. }

使用JsonObject来构建,可选择以下三种方式: 
方式一:

隐藏行号 复制代码 ? C#
  1. //通过标准构造函数
    
  2. JsonObject json = new JsonObject();
    
  3. json["orders"] = new JsonProperty(new JsonObject());
    
  4. json["blog"] = new JsonProperty("http://www.cnblogs.com/xfrog");
    
  5. JsonObject config = json.Properties<JsonObject>("orders");
    
  6. json["orders"]["date"] = new JsonProperty(DateTime.Now.ToLongTimeString());
    
  7. json["orders"]["name"] = new JsonProperty("Xfrog");
    
  8. json["orders"]["books"] = new JsonProperty();
    
  9. JsonProperty book = json["orders"]["books"].Add(new JsonObject());
    
  10. book["name"] = new JsonProperty("C# 网络核心编程");
    
  11. book["publish"] = new JsonProperty("2010-3-24");
    
  12. book = json["orders"]["books"].Add(new JsonObject());
    
  13. book["name"] = new JsonProperty("C#入门经典中文版");
    
  14. book["publish"] = new JsonProperty("2009-10-16");
    

方式二:

隐藏行号 复制代码 ? C#
  1. //通过回调函数简化对象的构建
    
  2. JsonObject json2 = new JsonObject((a) =>
    
  3. {
    
  4.     a["orders"] = new JsonProperty(new JsonObject((b) =>
    
  5.     {
    
  6.         b["date"] = new JsonProperty(DateTime.Now.ToLongTimeString());
    
  7.         b["name"] = new JsonProperty("Xfrog");
    
  8.         b["books"] = new JsonProperty();
    
  9.         b["books"].Add(new JsonObject((c) =>
    
  10.         {
    
  11.             c["name"] = new JsonProperty("C# 网络核心编程");
    
  12.             c["publish"] = new JsonProperty("2010-3-24");
    
  13.         }));
    
  14.         b["books"].Add(new JsonObject((c) =>
    
  15.         {
    
  16.             c["name"] = new JsonProperty("C#入门经典中文版");
    
  17.             c["publish"] = new JsonProperty("2009-10-16");
    
  18.         }));
    
  19.     }));
    
  20.     a["blog"] = new JsonProperty("http://www.cnblogs.com/xfrog");
    
  21. });
    

方式三:

隐藏行号 复制代码 ? C#
  1. //通过字符串构建Json对象
    
  2. JsonObject newObj = new JsonObject(jsonStr);
    

获取Json对象属性值的方法,也有三种方式:

隐藏行号 复制代码 ? C#
  1. //通过泛型函数
    
  2. Console.WriteLine(newObj["orders"].GetValue<JsonObject>()["books"].GetValue<List<JsonProperty>>()[1].GetValue<JsonObject>()["name"].Value);
    
  3. //通过属性类型对应的属性
    
  4. Console.WriteLine(newObj["orders"].Object["books"].Items[1].Object["name"].Value);
    
  5. //如果属性为对象类型,可通过字符串索引简化
    
  6. Console.WriteLine(newObj["orders"]["books"][1]["name"].Value);
    
    通用类:代码
    /**********************************************************
     * 作者:wHaibo
     * Email:xfrogcn@163.com
     * 日期:2010-04-07
     * 版本:1.0
     * 说明:Json通用转换类
     *********************************************************/
     
    using System;
    using System.Collections.Generic;
    using System.Text;
     
    namespace Xfrog.Net
    {
     
        /// <summary>
        /// 用于构建属性值的回调
        /// </summary>
        /// <param name="Property"></param>
        public delegate void SetProperties(JsonObject Property);
     
        /// <summary>
        /// JsonObject属性值类型
        /// </summary>
        public enum JsonPropertyType
        {
            String,
            Object,
            Array,
            Number,
            Bool,
            Null
        }
     
        /// <summary>
        /// JSON通用对象
        /// </summary>
        public class JsonObject
        {
            private Dictionary<String, JsonProperty> _property;
     
            public JsonObject()
            {
                this._property = null;
            }
     
            public JsonObject(String jsonString)
            {
                this.Parse(ref jsonString);
            }
     
            public JsonObject(SetProperties callback)
            {
                if (callback != null)
                {
                    callback(this);
                }
            }
     
            /// <summary>
            /// Json字符串解析
            /// </summary>
            /// <param name="jsonString"></param>
            private void Parse(ref String jsonString)
            {
                int len = jsonString.Length;
                bool poo = string.IsNullOrEmpty(jsonString);
                string po = jsonString.Substring(0, 1);
                string ll = jsonString.Substring(jsonString.Length - 1, 1);
                if (String.IsNullOrEmpty(jsonString) || jsonString.Substring(0, 1) != "{" || jsonString.Substring(jsonString.Length - 1, 1) != "}")
                {
                    throw new ArgumentException("传入文本不符合Json格式!" + jsonString);
                }
                Stack<Char> stack = new Stack<char>();
                Stack<Char> stackType = new Stack<char>();
                StringBuilder sb = new StringBuilder();
                Char cur;
                bool convert = false;
                bool isValue = false;
                JsonProperty last = null;
                for (int i = 1; i <= len - 2; i++)
                {
                    cur = jsonString[i];
                    if (cur == '}')
                    {
                        ;
                    }
                    if (cur == ' ' && stack.Count == 0)
                    {
                        ;
                    }
                    else if ((cur == '\'' || cur == '\"') && !convert && stack.Count == 0 && !isValue)
                    {
                        sb.Length = 0;
                        stack.Push(cur);
                    }
                    else if ((cur == '\'' || cur == '\"') && !convert && stack.Count > 0 && stack.Peek() == cur && !isValue)
                    {
                        stack.Pop();
                    }
                    else if ( (cur == '[' || cur == '{') && stack.Count == 0)
                    {
                        stackType.Push(cur == '[' ? ']' : '}');
                        sb.Append(cur);
                    }
                    else if ((cur == ']' || cur == '}') && stack.Count == 0 && stackType.Peek() == cur)
                    {
                        stackType.Pop();
                        sb.Append(cur);
                    }
                    else if (cur == ':' && stack.Count == 0 && stackType.Count == 0 && !isValue)
                    {
                        last = new JsonProperty();
                        this[sb.ToString()] = last;
                        isValue = true;
                        sb.Length = 0;
                    }
                    else if (cur == ',' && stack.Count == 0 && stackType.Count == 0)
                    {
                        if (last != null)
                        {
                             
                            String temp = sb.ToString();
                            last.Parse(ref temp);
                        }
                        isValue = false;
                        sb.Length = 0;
                    }
                    else
                    {
                        sb.Append(cur);
                    }
                }
                if (sb.Length > 0 && last != null && last.Type == JsonPropertyType.Null)
                {
                    String temp = sb.ToString();
                    last.Parse(ref temp);
                }
            }
     
            /// <summary>
            /// 获取属性
            /// </summary>
            /// <param name="PropertyName"></param>
            /// <returns></returns>
            public JsonProperty this[String PropertyName]
            {
                get
                {
                    JsonProperty result = null;
                    if (this._property != null && this._property.ContainsKey(PropertyName))
                    {
                        result = this._property[PropertyName];
                    }
                    return result;
                }
                set
                {
                    if (this._property == null)
                    {
                        this._property = new Dictionary<string, JsonProperty>(StringComparer.OrdinalIgnoreCase);
                    }
                    if (this._property.ContainsKey(PropertyName))
                    {
                        this._property[PropertyName] = value;
                    }
                    else
                    {
                        this._property.Add(PropertyName, value);
                    }
                }
            }
     
            /// <summary>
            /// 通过此泛型函数可直接获取指定类型属性的值
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <param name="PropertyName"></param>
            /// <returns></returns>
            public virtual T Properties<T>(String PropertyName) where T : class
            {
                JsonProperty p = this[PropertyName];
                if (p != null)
                {
                    return p.GetValue<T>();
                }
                return default(T);
            }
             
            /// <summary>
            /// 获取属性名称列表
            /// </summary>
            /// <returns></returns>
            public String[] GetPropertyNames()
            {
                if (this._property == null)
                    return null;
                String[] keys = null;
                if (this._property.Count > 0)
                {
                    keys = new String[this._property.Count];
                    this._property.Keys.CopyTo(keys, 0);
                }
                return keys;
            }
     
            /// <summary>
            /// 移除一个属性
            /// </summary>
            /// <param name="PropertyName"></param>
            /// <returns></returns>
            public JsonProperty RemoveProperty(String PropertyName)
            {
                if (this._property != null && this._property.ContainsKey(PropertyName))
                {
                    JsonProperty p = this._property[PropertyName];
                    this._property.Remove(PropertyName);
                    return p;
                }
                return null;
            }
     
            /// <summary>
            /// 是否为空对象
            /// </summary>
            /// <returns></returns>
            public bool IsNull()
            {
                return this._property == null;
            }
     
            public override string ToString()
            {
                return this.ToString("");
            }
     
            /// <summary>
            /// ToString...
            /// </summary>
            /// <param name="format">格式化字符串</param>
            /// <returns></returns>
            public virtual string ToString(String format)
            {
                if (this.IsNull())
                {
                    return "{}";
                }
                else
                {
                    StringBuilder sb = new StringBuilder();
                    foreach (String key in this._property.Keys)
                    {
                        sb.Append(",");
                        sb.Append(key).Append(": ");
                        sb.Append(this._property[key].ToString(format));
     
                    }
                    if (this._property.Count > 0)
                    {
                        sb.Remove(0, 1);
                    }
                    sb.Insert(0, "{");
                    sb.Append("}");
                    return sb.ToString();
                }
            }
        }
     
        /// <summary>
        /// JSON对象属性
        /// </summary>
        public class JsonProperty
        {
            private JsonPropertyType _type;
            private String _value;
            private JsonObject _object;
            private List<JsonProperty> _list;
            private bool _bool;
            private double _number;
     
            public JsonProperty()
            {
                this._type = JsonPropertyType.Null;
                this._value = null;
                this._object = null;
                this._list = null;
            }
     
            public JsonProperty(Object value)
            {
                this.SetValue(value);
            }
     
     
            public JsonProperty(String jsonString)
            {
                this.Parse(ref jsonString);
            }
      
     
            /// <summary>
            /// Json字符串解析
            /// </summary>
            /// <param name="jsonString"></param>
            public void Parse(ref String jsonString)
            {
                if (String.IsNullOrEmpty(jsonString))
                {
                    this.SetValue(null);
                }
                else
                {
                    string first = jsonString.Substring(0, 1);
                    string last = jsonString.Substring(jsonString.Length - 1, 1);
                    if (first == "[" && last == "]")
                    {
                        this.SetValue(this.ParseArray(ref jsonString));
                    }
                    else if (first == "{" && last=="}")
                    {
                        this.SetValue(this.ParseObject(ref jsonString));
                    }
                    else if ((first == "'" || first == "\"") && first == last)
                    {
                       this.SetValue( this.ParseString(ref jsonString));
                    }
                    else if (jsonString == "true" || jsonString == "false")
                    {
                        this.SetValue(jsonString == "true" ? true : false);
                    }
                    else if (jsonString == "null")
                    {
                        this.SetValue(null);
                    }
                    else
                    {
                        double d = 0;
                        if (double.TryParse(jsonString, out d))
                        {
                            this.SetValue(d);
                        }
                        else
                        {
                            this.SetValue(jsonString);
                        }
                    }
                }
            }
     
            /// <summary>
            /// Json Array解析
            /// </summary>
            /// <param name="jsonString"></param>
            /// <returns></returns>
            private List<JsonProperty> ParseArray(ref String jsonString)
            {
                List<JsonProperty> list = new List<JsonProperty>();
                int len = jsonString.Length;
                StringBuilder sb = new StringBuilder();
                Stack<Char> stack = new Stack<char>();
                Stack<Char> stackType = new Stack<Char>();
                bool conver = false;
                Char cur;
                for (int i = 1; i <= len - 2; i++)
                {
                    cur = jsonString[i];
                    if (Char.IsWhiteSpace(cur) && stack.Count == 0)
                    {
                        ;
                    }
                    else if ((cur == '\'' && stack.Count == 0 && !conver && stackType.Count == 0) || (cur == '\"' && stack.Count == 0 && !conver && stackType.Count == 0))
                    {
                        sb.Length = 0;
                        sb.Append(cur);
                        stack.Push(cur);
                    }
                    else if (cur == '\\' && stack.Count > 0 && !conver)
                    {
                        sb.Append(cur);
                        conver = true;
                    }
                    else if (conver == true)
                    {
                        conver = false;
     
                        if (cur == 'u')
                        {
                            sb.Append(new char[] { cur, jsonString[i + 1], jsonString[i + 2], jsonString[i + 3] });
                            i += 4;
                        }
                        else
                        {
                            sb.Append(cur);
                        }
                    }
                    else if ((cur == '\'' || cur == '\"') && !conver && stack.Count>0 && stack.Peek() == cur && stackType.Count == 0)
                    {
                        sb.Append(cur);
                        list.Add(new JsonProperty(sb.ToString()));
                        stack.Pop();
                    }else if( (cur == '[' || cur == '{' ) && stack.Count==0 )
                    {
                        if (stackType.Count == 0)
                        {
                            sb.Length = 0;
                        }
                        sb.Append( cur);
                        stackType.Push((cur == '[' ? ']' : '}'));
                    }
                    else if ((cur == ']' || cur == '}') && stack.Count == 0 && stackType.Count>0 && stackType.Peek() == cur)
                    {
                        sb.Append(cur);
                        stackType.Pop();
                        if (stackType.Count == 0)
                        {
                            list.Add(new JsonProperty(sb.ToString()));
                            sb.Length = 0;
                        }
     
                    }
                    else if (cur == ',' && stack.Count == 0 && stackType.Count == 0)
                    {
                        if (sb.Length > 0)
                        {
                            list.Add(new JsonProperty(sb.ToString()));
                            sb.Length = 0;
                        }
                    }
                    else
                    {
                        sb.Append(cur);
                    }     
                }
                if (stack.Count > 0 || stackType.Count > 0)
                {
                    list.Clear();
                    throw new ArgumentException("无法解析Json Array对象!");
                }
                else if (sb.Length > 0)
                {
                    list.Add(new JsonProperty(sb.ToString()));
                }
                return list;
            }
     
     
            /// <summary>
            /// Json String解析
            /// </summary>
            /// <param name="jsonString"></param>
            /// <returns></returns>
            private String ParseString(ref String jsonString)
            {
                int len = jsonString.Length;
                StringBuilder sb = new StringBuilder();
                bool conver = false;
                Char cur;
                for (int i = 1; i <= len - 2; i++)
                {
                    cur = jsonString[i];
                    if (cur == '\\' && !conver)
                    {
                        conver = true;
                    }
                    else if (conver == true)
                    {
                        conver = false;
                        if (cur == '\\' || cur == '\"' || cur == '\'' || cur == '/')
                        {
                            sb.Append(cur);
                        }
                        else
                        {
                            if (cur == 'u')
                            {
                                String temp = new String(new char[] { cur, jsonString[i + 1], jsonString[i + 2], jsonString[i + 3] });
                                sb.Append((char)Convert.ToInt32(temp, 16));
                                i += 4;
                            }
                            else
                            {
                                switch (cur)
                                {
                                    case 'b':
                                        sb.Append('\b');
                                        break;
                                    case 'f':
                                        sb.Append('\f');
                                        break;
                                    case 'n':
                                        sb.Append('\n');
                                        break;
                                    case 'r':
                                        sb.Append('\r');
                                        break;
                                    case 't':
                                        sb.Append('\t');
                                        break;
                                }
                            }
                        }
                    }
                    else
                    {
                        sb.Append(cur);
                    }
                }
                return sb.ToString();
            }
     
            /// <summary>
            /// Json Object解析
            /// </summary>
            /// <param name="jsonString"></param>
            /// <returns></returns>
            private JsonObject ParseObject(ref String jsonString)
            {
                return new JsonObject(jsonString);
            }
     
            /// <summary>
            /// 定义一个索引器,如果属性是非数组的,返回本身
            /// </summary>
            /// <param name="index"></param>
            /// <returns></returns>
            public JsonProperty this[int index]
            {
                get
                {
                    JsonProperty r = null;
                    if (this._type == JsonPropertyType.Array)
                    {
                        if (this._list != null && (this._list.Count - 1) >= index)
                        {
                            r = this._list[index];
                        }
                    }
                    else if (index == 0)
                    {
                        return this;
                    }
                    return r;
                }
            }
     
            /// <summary>
            /// 提供一个字符串索引,简化对Object属性的访问
            /// </summary>
            /// <param name="PropertyName"></param>
            /// <returns></returns>
            public JsonProperty this[String PropertyName]
            {
                get
                {
                    if (this._type == JsonPropertyType.Object)
                    {
                        return this._object[PropertyName];
                    }
                    else
                    {
                        return null;
                    }
                }
                set
                {
                    if (this._type == JsonPropertyType.Object)
                    {
                        this._object[PropertyName] = value;
                    }
                    else
                    {
                        throw new NotSupportedException("Json属性不是对象类型!");
                    }
                }
            }
     
            /// <summary>
            /// JsonObject值
            /// </summary>
            public JsonObject Object
            {
                get
                {
                    if (this._type == JsonPropertyType.Object)
                        return this._object;
                    return null;
                }
            }
     
            /// <summary>
            /// 字符串值
            /// </summary>
            public String Value
            {
                get
                {
                    if (this._type == JsonPropertyType.String)
                    {
                        return this._value;
                    }
                    else if (this._type == JsonPropertyType.Number)
                    {
                        return this._number.ToString();
                    }
                    return null;
                }
            }
     
            public JsonProperty Add(Object value)
            {
                if (this._type != JsonPropertyType.Null && this._type != JsonPropertyType.Array)
                {
                    throw new NotSupportedException("Json属性不是Array类型,无法添加元素!");
                }
                if (this._list == null)
                {
                    this._list = new List<JsonProperty>();
                }
                JsonProperty jp = new JsonProperty(value);
                this._list.Add(jp);
                this._type = JsonPropertyType.Array;
                return jp;
            }
     
            /// <summary>
            /// Array值,如果属性是非数组的,则封装成只有一个元素的数组
            /// </summary>
            public List<JsonProperty> Items
            {
                get
                {
                    if (this._type == JsonPropertyType.Array)
                    {
                        return this._list;
                    }
                    else
                    {
                        List<JsonProperty> list = new List<JsonProperty>();
                        list.Add(this);
                        return list;
                    }
                }
            }
     
            /// <summary>
            /// 数值
            /// </summary>
            public double Number
            {
                get
                {
                    if (this._type == JsonPropertyType.Number)
                    {
                        return this._number;
                    }
                    else
                    {
                        return double.NaN;
                    }
                }
            }
     
            public void Clear()
            {
                this._type = JsonPropertyType.Null;
                this._value = String.Empty;
                this._object = null;
                if (this._list != null)
                {
                    this._list.Clear();
                    this._list = null;
                }
            }
     
            public Object GetValue()
            {
                if (this._type == JsonPropertyType.String)
                {
                    return this._value;
                }
                else if (this._type == JsonPropertyType.Object)
                {
                    return this._object;
                }
                else if (this._type == JsonPropertyType.Array)
                {
                    return this._list;
                }
                else if (this._type == JsonPropertyType.Bool)
                {
                    return this._bool;
                }
                else if (this._type == JsonPropertyType.Number)
                {
                    return this._number;
                }
                else
                {
                    return null;
                }
            }
     
            public virtual T GetValue<T>() where T : class
            {
                return (GetValue() as T);
            }
     
            public virtual void SetValue(Object value)
            {
                if (value is String)
                {
                    this._type = JsonPropertyType.String;
                    this._value = (String)value;
                }
                else if (value is List<JsonProperty>)
                {
                    this._list = ((List<JsonProperty>)value);
                    this._type = JsonPropertyType.Array;
                }
                else if (value is JsonObject)
                {
                    this._object = (JsonObject)value;
                    this._type = JsonPropertyType.Object;
                }
                else if (value is bool)
                {
                    this._bool = (bool)value;
                    this._type = JsonPropertyType.Bool;
                }
                else if (value == null)
                {
                    this._type = JsonPropertyType.Null;
                }
                else
                {
                    double d = 0;
                    if (double.TryParse(value.ToString(), out d))
                    {
                        this._number = d;
                        this._type = JsonPropertyType.Number;
                    }
                    else
                    {
                        throw new ArgumentException("错误的参数类型!");
                    }
                }
            }
     
            public virtual int Count
            {
                get
                {
                    int c = 0;
                    if (this._type == JsonPropertyType.Array)
                    {
                        if (this._list != null)
                        {
                            c = this._list.Count;
                        }
                    }
                    else
                    {
                        c = 1;
                    }
                    return c;
                }
            }
     
            public JsonPropertyType Type
            {
                get { return this._type; }
            }
     
            public override string ToString()
            {
                return this.ToString("");
            }
     
     
            public virtual string ToString(String format)
            {
                StringBuilder sb = new StringBuilder();
                if (this._type == JsonPropertyType.String)
                {
                    sb.Append("'").Append(this._value).Append("'");
                    return sb.ToString();
                }
                else if (this._type == JsonPropertyType.Bool)
                {
                    return this._bool ? "true" : "false";
                }
                else if (this._type == JsonPropertyType.Number)
                {
                    return this._number.ToString();
                }
                else if (this._type == JsonPropertyType.Null)
                {
                    return "null";
                }
                else if (this._type == JsonPropertyType.Object)
                {
                    return this._object.ToString();
                }
                else
                {
                    if (this._list == null || this._list.Count == 0)
                    {
                        sb.Append("[]");
                    }
                    else
                    {
                        sb.Append("[");
                        if (this._list.Count > 0)
                        {
                            foreach (JsonProperty p in this._list)
                            {
                                sb.Append(p.ToString());
                                sb.Append(", ");
                            }
                            sb.Length-=2;
                        }
                        sb.Append("]");
                    }
                    return sb.ToString();
                }
            }
        }
    }
    
    

      

    
    

      

直接使用ToString函数,将JsonObject转换为Json字符串:

隐藏行号 复制代码 ? C#
  1. String jsonStr = json.ToString();
    

注意:

我在重载ToString函数时,并没有将字符串转换为JavsScript字符串类型(即对需要转义的字符的处理),当然,要实现也是极其简单的。另外,对于带String参数的ToString,我也为做特殊处理,感兴趣的朋友可自行实现。

Technorati 标签: .NET,JSON,C#

源代码下载

C#处理Json文件

 
 JSON(全称为JavaScript Object Notation) 是一种轻量级的数据交换格式。它是基于JavaScript语法标准的一个子集。 JSON采用完全独立于语言的文本格式,可以很容易在各种网络、平台和程序之间传输。JSON的语法很简单,易于人阅读和编写,同时也易于机器解析和生成。
  
JSON与XML的比较
◆可读性
  JSON和XML的可读性相比较而言,由于XML提供辅助的标签,更加适合人阅读和理解。
◆文件大小与传输
  XML允许使用方便的标签,所以文件尺寸是要比JSON大的。而且JSON源于Javascript,所以天生的主战场是Javascript与网络,在这里,JSON有着XML无法赶超的优势。
  
JSON语法
1. JSON 语法是 JavaScript 对象表示法语法的子集。
 •数据在名称/值对中:名称是字符串,使用双引号表示。值可以是:数字(整数或浮点数),字符串(在双引号中),数组(在方括号中),对象(在花括号中),true/false/null
•数据由逗号分隔:
•花括号保存对象:对象可以包含各种数据,包括数组。
•方括号保存数组:数字可以包含对象。
  
例如:
  
 
{
    "employees": [
        {
            "firstName": "Bill",
            "lastName": "Gates"
        },
        {
            "firstName": "George",
            "lastName": "Bush"
        }
    ]
}
 
复制代码
  
2. 如果JSON中含有转义字符,则需要转义。例如文件路径中需要使用"\\"而不是"\"。例如:{ "file":"C:\\a.txt"}。
  
  
  
.NET操作JSON
  JSON文件读入到内存中就是字符串,.NET操作JSON就是生成与解析JSON字符串。操作JSON通常有以下几种方式:
1. 原始方式:自己按照JSON的语法格式,写代码直接操作JSON字符串。如非必要,应该很少人会走这条路,从头再来的。
2. 通用方式:这种方式是使用开源的类库Newtonsoft.Json(下载地址http://json.codeplex.com/)。下载后加入工程就能用。通常可以使用JObject, JsonReader, JsonWriter处理。这种方式最通用,也最灵活,可以随时修改不爽的地方。
(1)使用JsonReader读Json字符串:
  
 
string jsonText = @"{""input"" : ""value"", ""output"" : ""result""}";
JsonReader reader = new JsonTextReader(new StringReader(jsonText));
 
while (reader.Read())
{
    Console.WriteLine(reader.TokenType + "\t\t" + reader.ValueType + "\t\t" + reader.Value);
}
 
复制代码
  
(2)使用JsonWriter写字符串:
  
 
StringWriter sw = new StringWriter();
JsonWriter writer = new JsonTextWriter(sw);
 
writer.WriteStartObject();
writer.WritePropertyName("input");
writer.WriteValue("value");
writer.WritePropertyName("output");
writer.WriteValue("result");
writer.WriteEndObject();
writer.Flush();
 
string jsonText = sw.GetStringBuilder().ToString();
Console.WriteLine(jsonText);
 
复制代码
  
(3)使用JObject读写字符串:
  
 
JObject jo = JObject.Parse(jsonText);
string[] values = jo.Properties().Select(item => item.Value.ToString()).ToArray();
 
复制代码
  
(4)使用JsonSerializer读写对象(基于JsonWriter与JsonReader):
  
 
Project p = new Project() { Input = "stone", Output = "gold" };
JsonSerializer serializer = new JsonSerializer();
StringWriter sw = new StringWriter();
serializer.Serialize(new JsonTextWriter(sw), p);
Console.WriteLine(sw.GetStringBuilder().ToString());
 
StringReader sr = new StringReader(@"{""Input"":""stone"", ""Output"":""gold""}");
Project p1 = (Project)serializer.Deserialize(new JsonTextReader(sr), typeof(Project));
Console.WriteLine(p1.Input + "=>" + p1.Output);
 
复制代码
  
  上面的代码都是基于下面这个Project类定义:
  
 
class Project
{
    public string Input { get; set; }
    public string Output { get; set; }
}
 
复制代码
  
  此外,如果上面的JsonTextReader等类编译不过的话,说明是我们自己修改过的类,换成你们自己的相关类就可以了,不影响使用。
3. 内置方式:使用.NET Framework 3.5/4.0中提供的System.Web.Script.Serialization命名空间下的JavaScriptSerializer类进行对象的序列化与反序列化,很直接。
  
 
 Project p = new Project() { Input = "stone", Output = "gold" };
 JavaScriptSerializer serializer = new JavaScriptSerializer();
 var json = serializer.Serialize(p);
 Console.WriteLine(json);
 
 var p1 = serializer.Deserialize<Project>(json);
 Console.WriteLine(p1.Input + "=>" + p1.Output);
 Console.WriteLine(ReferenceEquals(p,p1));
 
复制代码
  
  注意:如果使用的是VS2010,则要求当前的工程的Target Framework要改成.Net Framework 4,不能使用Client Profile。当然这个System.Web.Extensions.dll主要是Web使用的,直接在Console工程中用感觉有点浪费资源。
  此外,从最后一句也可以看到,序列化与反序列化是深拷贝的一种典型的实现方式。
  
4. 契约方式:使用System.Runtime.Serialization.dll提供的DataContractJsonSerializer或者 JsonReaderWriterFactory实现。
  
 
Project p = new Project() { Input = "stone", Output = "gold" };
DataContractJsonSerializer serializer = new DataContractJsonSerializer(p.GetType());
string jsonText;
 
using (MemoryStream stream = new MemoryStream())
{
    serializer.WriteObject(stream, p);
    jsonText = Encoding.UTF8.GetString(stream.ToArray());
    Console.WriteLine(jsonText);
}
 
using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonText)))
{
    DataContractJsonSerializer serializer1 = new DataContractJsonSerializer(typeof(Project));
    Project p1 = (Project)serializer1.ReadObject(ms);
    Console.WriteLine(p1.Input + "=>" + p1.Output);
}
 
复制代码
  
  这里要注意,这里的Project类和成员要加相关的Attribute:
  
 
[DataContract]
class Project
{
    [DataMember]
    public string Input { get; set; }
    [DataMember]
    public string Output { get; set; }
}
 
复制代码
  
 
实用参考:
JSON验证工具:http://jsonlint.com/
JSON简明教程:http://www.w3school.com.cn/json/
Newtonsoft.Json类库下载:http://json.codeplex.com/

  

asp.net使用Jquery+iframe传值问题

 
 
使用asp.net技术开发一个a.aspx和b.aspx。a页面显示数据列表,并且可以实现多项选择."发送"按钮使用服务器控件,选择相应的数据列表项,点击"发送"按钮传递ID参数到b页面接收
OnClientClick=<%# "OpenWindow('"+Eval("Id")+"', 700,250);return false;" %>
     
<SCRIPT src="js/ui.mouse.js" type=text/javascript></SCRIPT>
  <SCRIPT src="js/ui.draggable.js" type=text/javascript></SCRIPT>
  <SCRIPT src="js/jquery.jwindow.js" type=text/javascript></SCRIPT>
  <script>
 function OpenWindow(id,width,height) {
  var p = document.getElementById("<%=hf_Id.ClientID %>").value;
  var url = "a.aspx?Id=" + id + "&pId=" + p;
  SetTitle(url);
  OpenJWindow('#openwin', url, width, height, EditClosed);
}
function SetTitle(url)
{
  var obj = document.getElementById("winTitle");
     
  if(url.lastIndexOf("Id") >0){
  obj.innerHTML ="编辑";
  return;
  }  
  obj.innerHTML ="新增";
}
function EditClosed(result) {
 
  if (result == "0") return;
  return false;
}