001 |
using System;
|
002 |
using System.Collections.Generic;
|
003 |
using System.Linq;
|
004 |
using System.Text;
|
005 |
using System.Data;
|
006 |
|
007 |
namespace Common
|
008 |
|
009 |
|
010 |
public static class JsonExtensions
|
011 |
|
012 |
#region DataSetToJson 扩展方法
|
013 |
/// <summary>
|
014 |
/// DataSetToJson 扩展方法
|
015 |
/// </summary>
|
016 |
/// <param name="ds">要传入的DataSet</param>
|
017 |
/// <param name="JsonName">Json的名称</param>
|
018 |
/// <param name="ParName">Json字段名称</param>
|
019 |
/// <returns>返回JSON字符串</returns>
|
020 |
public static string DataSetToJson( this DataSet ds, string JsonName, string [] ParName)
|
021 |
|
022 |
try
|
023 |
|
024 |
if (ds == null
|
025 |
|
026 |
return "DataSet Is Null ,So I Can't Do It To Json!"
|
027 |
|
028 |
if (JsonName.Length < 1)
|
029 |
|
030 |
return "You Set The Json Name Is Wrong!"
|
031 |
|
032 |
if (ds.Tables[0].Columns.Count < ParName.Length)
|
033 |
|
034 |
return "You Give The ParName Is Bigger Than DataSet Columns!"
|
035 |
|
036 |
string josn = "{" + JsonName + ":["
|
037 |
string temp = ""
|
038 |
for ( int j = 0; j < ds.Tables[0].Rows.Count; j++)
|
039 |
|
040 |
temp = temp + "{"
|
041 |
for ( int i = 0; i < ParName.Length; i++)
|
042 |
|
043 |
temp += "" + ParName[i] + ":\'" + ds.Tables[0].Rows[j][ParName[i]] + "\'"
|
044 |
if (i != ParName.Length - 1)
|
045 |
|
046 |
temp = temp + ","
|
047 |
|
048 |
|
049 |
if (j == ds.Tables[0].Rows.Count - 1)
|
050 |
|
051 |
temp = temp + "}"
|
052 |
|
053 |
else
|
054 |
|
055 |
temp = temp + "},"
|
056 |
|
057 |
|
058 |
josn = josn + temp + "]}"
|
059 |
return josn;
|
060 |
|
061 |
catch (Exception ex)
|
062 |
|
063 |
return "Codeing is Error----" + ex.ToString();
|
064 |
|
065 |
|
066 |
|
067 |
|
068 |
#endregion
|
069 |
|
070 |
#region DataSetToJson 扩展方法
|
071 |
/// <summary>
|
072 |
/// DataSetToJson 扩展方法
|
073 |
/// </summary>
|
074 |
/// <param name="ds">要传入的DataSet</param>
|
075 |
/// <returns>返回JSON字符串<</returns>
|
076 |
public static string DataSetToJson( this DataSet ds)
|
077 |
|
078 |
try
|
079 |
|
080 |
if (ds == null
|
081 |
|
082 |
return "DataSet Is Null ,So I Can't Do It To Json!"
|
083 |
|
084 |
string josn = "["
|
085 |
string temp = ""
|
086 |
for ( int j = 0; j < ds.Tables[0].Rows.Count; j++)
|
087 |
|
088 |
temp = temp + "{"
|
089 |
for ( int i = 0; i < ds.Tables[0].Columns.Count; i++)
|
090 |
|
091 |
temp += "" + ds.Tables[0].Columns[i].ColumnName + ":\'" + ds.Tables[0].Rows[j][i] + "\'"
|
092 |
if (i != ds.Tables[0].Columns.Count - 1)
|
093 |
|
094 |
temp = temp + ","
|
095 |
|
096 |
|
097 |
if (j == ds.Tables[0].Rows.Count - 1)
|
098 |
|
099 |
temp = temp + "}"
|
100 |
|
101 |
else
|
102 |
|
103 |
temp = temp + "},"
|
104 |
|
105 |
|
106 |
josn = josn + temp + "]"
|
107 |
return josn;
|
108 |
|
109 |
catch (Exception ex)
|
110 |
|
111 |
return "Codeing is Error----" + ex.ToString();
|
112 |
|
113 |
|
114 |
|
115 |
#endregion
|
116 |
|
117 |
} |