四個主要操作類:JsonConverter 、JsonHelper 、JSonSplit 、AJaxResult
一、JSonConverter:
自定義查詢對象轉換動態類、object動態類轉換json包、json轉換object動態類、DataReader轉換為Json、DataSet轉換為Json、DataTable轉成Json、Datatable轉換為JSon 、格式化字符型日期型布爾型、過濾特殊字符等
? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464using
System;
using
System.Collections.Generic;
using
System.Text;
using
System.Data;
using
System.Linq;
using
System.Web.Script.Serialization;
using
System.Collections;
namespace
Common
{
public
class
JSonConverter
{
/// <summary>
/// 自定義查詢對象轉換動態類
/// add yuangang by 2015-05-19
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public
static
dynamic JSonClass(
object
obj)
{
return
ConvertJSon(Serialize(obj,
true
));
}
/// <summary>
/// object動態類轉換JSon包
/// add yuangang by 2015-05-19
/// </summary>
/// <param name="obj">對象</param>
/// <param name="DateConvert">時間戳是否轉換成日期類型</param>
/// <returns></returns>
public
static
string
Serialize(
object
obj,
bool
DateConvert =
false
)
{
JavaScriptSerializer JSs =
new
JavaScriptSerializer();
var str = JSs.Serialize(obj);
if
(DateConvert)
{
str = System.Text.RegularExpressions.Regex.Replace(str,
@"\\/Date\((\d+)\)\\/"
, match =>
{
DateTime dt =
new
DateTime(1970, 1, 1);
dt = dt.AddMilliseconds(
long
.Parse(match.Groups[1].Value));
dt = dt.ToLocalTime();
return
dt.ToString(
"yyyy-MM-dd HH:mm:ss"
);
});
}
return
str;
}
/// <summary>
/// JSon轉換object動態類
/// add yuangang by 2015-05-19
/// </summary>
/// <param name="JSon"></param>
/// <returns></returns>
public
static
dynamic ConvertJSon(
string
JSon)
{
JavaScriptSerializer JSs =
new
JavaScriptSerializer();
JSs.RegisterConverters(
new
JavaScriptConverter[] {
new
DynamicJSonConverter() });
dynamic dy = jss.Deserialize(JSon,
typeof
(
object
))
as
dynamic;
return
dy;
}
/// <summary>
/// DataReader轉換為JSon
/// </summary>
/// <param name="dataReader">DataReader對象</param>
/// <returns>JSon字符串</returns>
public
static
string
ToJSon(IDataReader dataReader)
{
try
{
StringBuilder JSonString =
new
StringBuilder();
JSonString.Append(
"["
);
while
(dataReader.Read())
{
JSonString.Append(
"{"
);
for
(
int
i = 0; i < dataReader.FIEldCount; i++)
{
Type type = dataReader.GetFIEldType(i);
string
strKey = dataReader.GetName(i);
string
strValue = dataReader[i].ToString();
JSonString.Append(
"\""
+ strKey +
"\":"
);
strValue = StringFormat(strValue, type);
if
(i < dataReader.FIEldCount - 1)
{
JSonString.Append(strValue +
","
);
}
else
{
JSonString.Append(strValue);
}
}
JSonString.Append(
"},"
);
}
if
(!dataReader.IsClosed)
{
dataReader.Close();
}
jsonString.Remove(JSonString.Length - 1, 1);
JSonString.Append(
"]"
);
if
(JSonString.Length == 1)
{
return
"[]"
;
}
return
JSonString.ToString();
}
catch
(Exception ex)
{
throw
ex;
}
}
/// <summary>
/// DataSet轉換為JSon
/// add yuangang by 2015-05-19
/// </summary>
/// <param name="dataSet">DataSet對象</param>
/// <returns>JSon字符串</returns>
public
static
string
ToJSon(DataSet dataSet)
{
string
JSonString =
"{"
;
foreach
(DataTable table
in
dataSet.Tables)
{
JSonString +=
"\""
+ table.TableName +
"\":"
+ ToJSon(table) +
","
;
}
jsonString = JSonString.TrimEnd(
','
);
return
JSonString +
"}"
;
}
/// <summary>
/// DataTable轉成JSon
/// add yuangang by 2015-05-19
/// </summary>
/// <param name="JSonName"></param>
/// <param name="dt"></param>
/// <returns></returns>
public
static
string
ToJSon(DataTable dt,
string
JSonName)
{
StringBuilder JSon =
new
StringBuilder();
if
(
string
.IsNullOrEmpty(JSonName))
JSonName = dt.TableName;
JSon.Append(
"{\""
+ JSonName +
"\":["
);
if
(dt.Rows.Count > 0)
{
for
(
int
i = 0; i < dt.Rows.Count; i++)
{
JSon.Append(
"{"
);
for
(
int
j = 0; j < dt.Columns.Count; j++)
{
Type type = dt.Rows[i][j].GetType();
JSon.Append(
"\""
+ dt.Columns[j].ColumnName.ToString() +
"\":"
+ StringFormat(dt.Rows[i][j]
is
DBNull ?
string
.Empty : dt.Rows[i][j].ToString(), type));
if
(j < dt.Columns.Count - 1)
{
JSon.Append(
","
);
}
}
JSon.Append(
"}"
);
if
(i < dt.Rows.Count - 1)
{
JSon.Append(
","
);
}
}
}
JSon.Append(
"]}"
);
return
JSon.ToString();
}
/// <summary>
/// Datatable轉換為JSon
/// add yuangang by 2015-05-19
/// </summary>
/// <param name="table">Datatable對象</param>
/// <returns>JSon字符串</returns>
public
static
string
ToJSon(DataTable dt)
{
StringBuilder JSonString =
new
StringBuilder();
JSonString.Append(
"["
);
DataRowCollection drc = dt.Rows;
for
(
int
i = 0; i < drc.Count; i++)
{
JSonString.Append(
"{"
);
for
(
int
j = 0; j < dt.Columns.Count; j++)
{
string
strKey = dt.Columns[j].ColumnName;
string
strValue = drc[i][j].ToString();
Type type = dt.Columns[j].DataType;
JSonString.Append(
"\""
+ strKey +
"\":"
);
strValue = StringFormat(strValue, type);
if
(j < dt.Columns.Count - 1)
{
JSonString.Append(strValue +
","
);
}
else
{
JSonString.Append(strValue);
}
}
JSonString.Append(
"},"
);
}
jsonString.Remove(JSonString.Length - 1, 1);
JSonString.Append(
"]"
);
if
(JSonString.Length == 1)
{
return
"[]"
;
}
return
JSonString.ToString();
}
/// <summary>
/// 格式化字符型、日期型、布爾型
/// add yuangang by 2015-05-19
/// </summary>
/// <param name="str"></param>
/// <param name="type"></param>
/// <returns></returns>
private
static
string
StringFormat(
string
str, Type type)
{
if
(type !=
typeof
(
string
) &&
string
.IsNullOrEmpty(str))
{
str =
"\""
+ str +
"\""
;
}
else
if
(type ==
typeof
(
string
))
{
str = String2JSon(str);
str =
"\""
+ str +
"\""
;
}
else
if
(type ==
typeof
(DateTime))
{
str =
"\""
+ str +
"\""
;
}
else
if
(type ==
typeof
(
bool
))
{
str = str.ToLower();
}
else
if
(type ==
typeof
(
byte
[]))
{
str =
"\""
+ str +
"\""
;
}
else
if
(type ==
typeof
(Guid))
{
str =
"\""
+ str +
"\""
;
}
return
str;
}
/// <summary>
/// 過濾特殊字符
/// add yuangang by 2015-05-19
/// </summary>
/// <param name="s"></param>
/// <returns></returns>
public
static
string
String2JSon(String s)
{
StringBuilder sb =
new
StringBuilder();
for
(
int
i = 0; i < s.Length; i++)
{
char
c = s.ToCharArray()[i];
switch
(c)
{
case
'\"'
:
sb.Append(
"\\\""
);
break
;
case
'\\'
:
sb.Append(
"\\\\"
);
break
;
case
'/'
:
sb.Append(
"\\/"
);
break
;
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
;
case
'\v'
:
sb.Append(
"\\v"
);
break
;
case
'\0'
:
sb.Append(
"\\0"
);
break
;
default
:
sb.Append(c);
break
;
}
}
return
sb.ToString();
}
public
static
string
GetDataGridJSonByDataSet(DataSet ds,
string
totalProperty,
string
root)
{
return
GetDataGridJSonByDataTable(ds.Tables[0], totalProperty, root);
}
public
static
string
GetDataGridJSonByDataTable(DataTable dt,
string
totalProperty,
string
root)
{
StringBuilder JSonBuilder =
new
StringBuilder();
JSonBuilder.Append(
"({\""
+ totalProperty +
"\":\""
+ dt.Rows.Count +
"\","
);
JSonBuilder.Append(
"\""
);
JSonBuilder.Append(root);
JSonBuilder.Append(
"\":["
);
for
(
int
i = 0; i < dt.Rows.Count; i++)
{
JSonBuilder.Append(
"{"
);
for
(
int
j = 0; j < dt.Columns.Count; j++)
{
JSonBuilder.Append(
"\""
);
JSonBuilder.Append(dt.Columns[j].ColumnName);
JSonBuilder.Append(
"\":\""
);
JSonBuilder.Append(dt.Rows[i][j].ToString());
JSonBuilder.Append(
"\","
);
}
jsonBuilder.Remove(JSonBuilder.Length - 1, 1);
JSonBuilder.Append(
"},"
);
}
jsonBuilder.Remove(JSonBuilder.Length - 1, 1);
JSonBuilder.Append(
"]"
);
JSonBuilder.Append(
"})"
);
return
JSonBuilder.ToString();
}
public
static
string
GetTreeJSonByDataSet(DataSet ds)
{
return
GetTreeJSonByDataTable(ds.Tables[0]);
}
public
static
string
GetTreeJSonByDataTable(DataTable dataTable)
{
DataTable dt = FormatDataTableForTree(dataTable);
StringBuilder JSonBuilder =
new
StringBuilder();
JSonBuilder.Append(
"["
);
for
(
int
i = 0; i < dt.Rows.Count; i++)
{
JSonBuilder.Append(
"{"
);
for
(
int
j = 0; j < dt.Columns.Count; j++)
{
JSonBuilder.Append(
"\'"
);
if
(dt.Columns[j].ColumnName ==
"leaf"
)
{
string
leafValue = dt.Rows[i][j].ToString();
if
(!
string
.IsNullOrEmpty(leafValue))
{
JSonBuilder.Append(dt.Columns[j].ColumnName);
JSonBuilder.Append(
"\':\'"
);
JSonBuilder.Append(dt.Rows[i][j].ToString());
JSonBuilder.Append(
"\',"
);
}
else
{
jsonBuilder.Remove(JSonBuilder.Length - 1, 1);
}
}
else
if
(dt.Columns[j].ColumnName ==
"customUrl"
)
{
jsonBuilder.Remove(JSonBuilder.Length - 1, 1);
JSonBuilder.Append(dt.Columns[j].ColumnName);
JSonBuilder.Append(
":\'"
);
JSonBuilder.Append(dt.Rows[i][j].ToString());
JSonBuilder.Append(
"\',"
);
}
else
{
JSonBuilder.Append(dt.Columns[j].ColumnName);
JSonBuilder.Append(
"\':\'"
);
JSonBuilder.Append(dt.Rows[i][j].ToString());
JSonBuilder.Append(
"\',"
);
}
}
jsonBuilder.Remove(JSonBuilder.Length - 1, 1);
JSonBuilder.Append(
"},"
);
}
jsonBuilder.Remove(JSonBuilder.Length - 1, 1);
JSonBuilder.Append(
"]"
);
return
JSonBuilder.ToString();
}
private
static
DataTable FormatDataTableForTree(DataTable dt)
{
DataTable dtTree =
new
DataTable();
dtTree.Columns.Add(
"id"
,
typeof
(
string
));
dtTree.Columns.Add(
"text"
,
typeof
(
string
));
dtTree.Columns.Add(
"leaf"
,
typeof
(
string
));
dtTree.Columns.Add(
"cls"
,
typeof
(
string
));
dtTree.Columns.Add(
"customUrl"
,
typeof
(
string
));
dtTree.AcceptChanges();
for
(
int
i = 0; i < dt.Rows.Count; i++)
{
DataRow drTree = dtTree.NewRow();
drTree[
"id"
] = dt.Rows[i][
"id"
].ToString();
drTree[
"text"
] = dt.Rows[i][
"text"
].ToString();
if
(dt.Rows[i][
"leaf"
].ToString() ==
"Y"
)
{
drTree[
"leaf"
] =
"true"
;
drTree[
"cls"
] =
"file"
;
}
else
{
drTree[
"cls"
] =
"folder"
;
}
drTree[
"customUrl"
] = dt.Rows[i][
"customUrl"
].ToString();
dtTree.Rows.Add(drTree);
}
return
dtTree;
}
}
/// <summary>
/// 動態JSON解析
/// add yuangang by 2015-05-19
/// </summary>
public
class
DynamicJSonObject : System.Dynamic.DynamicObject
{
private
IDictionary<
string
,
object
> Dictionary {
get
;
set
; }
public
DynamicJSonObject(IDictionary<
string
,
object
> dictionary)
{
this
.Dictionary = dictionary;
}
public
override
bool
TryGetMember(System.Dynamic.GetMemberBinder binder,
out
object
result)
{
result =
this
.Dictionary[binder.Name];
if
(result
is
IDictionary<
string
,
object
>)
{
result =
new
DynamicJSonObject(result
as
IDictionary<
string
,
object
>);
}
else
if
(result
is
ArrayList && (result
as
ArrayList)
is
IDictionary<
string
,
object
>)
{
result =
new
List<DynamicJSonObject>((result
as
ArrayList).ToArray().Select(x =>
new
DynamicJSonObject(x
as
IDictionary<
string
,
object
>)));
}
else
if
(result
is
ArrayList)
{
result =
new
List<
object
>((result
as
ArrayList).ToArray());
}
return
this
.Dictionary.ContainsKey(binder.Name);
}
}
/// <summary>
/// 動態JSON轉換
/// add yuangang by 2015-05-19
/// </summary>
public
class
DynamicJSonConverter : JavaScriptConverter
{
public
override
object
Deserialize(IDictionary<
string
,
object
> dictionary, Type type, JavaScriptSerializer serializer)
{
if
(dictionary ==
null
)
throw
new
ArgumentNullException(
"dictionary"
);
if
(type ==
typeof
(
object
))
{
return
new
DynamicJSonObject(dictionary);
}
return
null
;
}
public
override
IDictionary<
string
,
object
> Serialize(
object
obj, JavaScriptSerializer serializer)
{
throw
new
NotImplementedException();
}
public
override
IEnumerable<Type> SupportedTypes
{
get
{
return
new
System.Collections.ObjectModel.ReadOnlyCollection<Type>(
new
List<Type>(
new
Type[] {
typeof
(
object
) })); }
}
}
}
二、JsonHelper:JSon的輔助類
? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89using
System.Collections.Generic;
using
System.Text;
using
Newtonsoft.JSon;
using
System.Runtime.Serialization.JSon;
using
System.IO;
namespace
Common
{
/// <summary>
/// 提供了一個關於JSon的輔助類
/// </summary>
public
class
JSonHelper
{
#region Method
/// <summary>
/// 類對像轉換成JSon格式
/// </summary>
/// <returns></returns>
public
static
string
ToJSon(
object
t)
{
return
JsonConvert.SerializeObject(t, Newtonsoft.JSon.Formatting.Indented,
new
JSonSerializerSettings { NullValueHandling = NullValueHandling.Include });
}
/// <summary>
/// 類對像轉換成JSon格式
/// </summary>
/// <param name="t"></param>
/// <param name="HasNullIgnore">是否忽略NULL值</param>
/// <returns></returns>
public
static
string
ToJSon(
object
t,
bool
HasNullIgnore)
{
if
(HasNullIgnore)
return
JsonConvert.SerializeObject(t, Newtonsoft.JSon.Formatting.Indented,
new
JSonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
else
return
ToJSon(t);
}
/// <summary>
/// JSon格式轉換
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="strJSon"></param>
/// <returns></returns>
public
static
T FromJSon<T>(
string
strJSon) where T :
class
{
if
(!strJSon.IsNullOrEmpty())
return
JsonConvert.DeserializeObject<T>(strJSon);
return
null
;
}
/// <summary>
/// 功能描述:將List轉換為JSon
/// </summary>
/// <param name="a"></param>
/// <returns></returns>
public
static
string
ListToJSon(IList<
object
> a)
{
DataContractJsonSerializer JSon =
new
DataContractJSonSerializer(a.GetType());
string
szJSon =
""
;
//序列化
using
(MemoryStream stream =
new
MemoryStream())
{
JSon.WriteObject(stream, a);
szJSon = Encoding.UTF8.GetString(stream.ToArray());
}
return
szJSon;
}
#endregion
#region Property
/// <summary>
/// 數據狀態
/// </summary>
public
string
Status {
get
;
set
; }
/// <summary>
/// 提示信息
/// </summary>
public
string
Msg {
get
;
set
; }
/// <summary>
/// 回傳URL
/// </summary>
public
string
ReUrl {
get
;
set
; }
/// <summary>
/// 數據包
/// </summary>
public
object
Data {
get
;
set
; }
#endregion
}
}
三、JsonSplit:判斷字符串是否為JSon
? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406using
System;
using
System.Collections.Generic;
using
System.Linq;
using
System.Web;
namespace
Common
{
/// <summary>
/// 判斷字符串是否為JSON
/// </summary>
public
class
JSonSplit
{
private
static
bool
IsJSonStart(
ref
string
JSon)
{
if
(!
string
.IsNullOrEmpty(JSon))
{
json = JSon.Trim(
'\r'
,
'\n'
,
' '
);
if
(JSon.Length > 1)
{
char
s = JSon[0];
char
e = json[JSon.Length - 1];
return
(s ==
'{'
&& e ==
'}'
) || (s ==
'['
&& e ==
']'
);
}
}
return
false
;
}
public
static
bool
IsJSon(
string
JSon)
{
int
errIndex;
return
IsJson(JSon,
out
errIndex);
}
public
static
bool
IsJSon(
string
JSon,
out
int
errIndex)
{
errIndex = 0;
if
(IsJSonStart(
ref
JSon))
{
CharState cs =
new
CharState();
char
c;
for
(
int
i = 0; i < JSon.Length; i++)
{
c = JSon[i];
if
(SetCharState(c,
ref
cs) && cs.childrenStart)
//設置關鍵符號狀態。
{
string
item = JSon.Substring(i);
int
err;
int
length = GetValueLength(item,
true
,
out
err);
cs.childrenStart =
false
;
if
(err > 0)
{
errIndex = i + err;
return
false
;
}
i = i + length - 1;
}
if
(cs.isError)
{
errIndex = i;
return
false
;
}
}
return
!cs.arrayStart && !cs.JSonStart;
}
return
false
;
}
/// <summary>
/// 獲取值的長度(當JSon值嵌套以"{"或"["開頭時)
/// </summary>
private
static
int
GetValueLength(
string
JSon,
bool
breakOnErr,
out
int
errIndex)
{
errIndex = 0;
int
len = 0;
if
(!
string
.IsNullOrEmpty(JSon))
{
CharState cs =
new
CharState();
char
c;
for
(
int
i = 0; i < JSon.Length; i++)
{
c = JSon[i];
if
(!SetCharState(c,
ref
cs))
//設置關鍵符號狀態。
{
if
(!cs.JSonStart && !cs.arrayStart)
//JSon結束,又不是數組,則退出。
{
break
;
}
}
else
if
(cs.childrenStart)
//正常字符,值狀態下。
{
int
length = GetValueLength(JSon.Substring(i), breakOnErr,
out
errIndex);
//遞歸子值,返回一個長度。。。
cs.childrenStart =
false
;
cs.valueStart = 0;
//cs.state = 0;
i = i + length - 1;
}
if
(breakOnErr && cs.isError)
{
errIndex = i;
return
i;
}
if
(!cs.JSonStart && !cs.arrayStart)
//記錄當前結束位置。
{
len = i + 1;
//長度比索引+1
break
;
}
}
}
return
len;
}
/// <summary>
/// 字符狀態
/// </summary>
private
class
CharState
{
internal
bool
JSonStart =
false
;
//以 "{"開始了...
internal
bool
setDicValue =
false
;
// 可以設置字典值了。
internal
bool
escapeChar =
false
;
//以"\"轉義符號開始了
/// <summary>
/// 數組開始【僅第一開頭才算】,值嵌套的以【childrenStart】來標識。
/// </summary>
internal
bool
arrayStart =
false
;
//以"[" 符號開始了
internal
bool
childrenStart =
false
;
//子級嵌套開始了。
/// <summary>
/// 【0 初始狀態,或 遇到“,”逗號】;【1 遇到“:”冒號】
/// </summary>
internal
int
state = 0;
/// <summary>
/// 【-1 取值結束】【0 未開始】【1 無引號開始】【2 單引號開始】【3 雙引號開始】
/// </summary>
internal
int
keyStart = 0;
/// <summary>
/// 【-1 取值結束】【0 未開始】【1 無引號開始】【2 單引號開始】【3 雙引號開始】
/// </summary>
internal
int
valueStart = 0;
internal
bool
isError =
false
;
//是否語法錯誤。
internal
void
CheckIsError(
char
c)
//只當成一級處理(因為GetLength會遞歸到每一個子項處理)
{
if
(keyStart > 1 || valueStart > 1)
{
return
;
}
//示例 ["aa",{"bbbb":123,"fff","ddd"}]
switch
(c)
{
case
'{'
:
//[{ "[{A}]":[{"[{B}]":3,"m":"C"}]}]
isError = JSonStart && state == 0;
//重復開始錯誤 同時不是值處理。
break
;
case
'}'
:
isError = !JSonStart || (keyStart != 0 && state == 0);
//重復結束錯誤 或者 提前結束{"aa"}。正常的有{}
break
;
case
'['
:
isError = arrayStart && state == 0;
//重復開始錯誤
break
;
case
']'
:
isError = !arrayStart || JSonStart;
//重復開始錯誤 或者 JSon 未結束
break
;
case
'"'
:
case
'\''
:
isError = !(JSonStart || arrayStart);
//JSon 或數組開始。
if
(!isError)
{
//重復開始 [""",{"" "}]
isError = (state == 0 && keyStart == -1) || (state == 1 && valueStart == -1);
}
if
(!isError && arrayStart && !JSonStart && c ==
'\''
)
//['aa',{}]
{
isError =
true
;
}
break
;
case
':'
:
isError = !JSonStart || state == 1;
//重復出現。
break
;
case
','
:
isError = !(JSonStart || arrayStart);
//JSon 或數組開始。
if
(!isError)
{
if
(JSonStart)
{
isError = state == 0 || (state == 1 && valueStart > 1);
//重復出現。
}
else
if
(arrayStart)
//["aa,] [,] [{},{}]
{
isError = keyStart == 0 && !setDicValue;
}
}
break
;
case
' '
:
case
'\r'
:
case
'\n'
:
//[ "a",\r\n{} ]
case
'\0'
:
case
'\t'
:
break
;
default
:
//值開頭。。
isError = (!JSonStart && !arrayStart) || (state == 0 && keyStart == -1) || (valueStart == -1 && state == 1);
//
break
;
}
//if (isError)
//{
//}
}
}
/// <summary>
/// 設置字符狀態(返回true則為關鍵詞,返回false則當為普通字符處理)
/// </summary>
private
static
bool
SetCharState(
char
c,
ref
CharState cs)
{
cs.CheckIsError(c);
switch
(c)
{
case
'{'
:
//[{ "[{A}]":[{"[{B}]":3,"m":"C"}]}]
#region 大括號
if
(cs.keyStart <= 0 && cs.valueStart <= 0)
{
cs.keyStart = 0;
cs.valueStart = 0;
if
(cs.JSonStart && cs.state == 1)
{
cs.childrenStart =
true
;
}
else
{
cs.state = 0;
}
cs.JSonStart =
true
;
//開始。
return
true
;
}
#endregion
break
;
case
'}'
:
#region 大括號結束
if
(cs.keyStart <= 0 && cs.valueStart < 2 && cs.JSonStart)
{
cs.JSonStart =
false
;
//正常結束。
cs.state = 0;
cs.keyStart = 0;
cs.valueStart = 0;
cs.setDicValue =
true
;
return
true
;
}
// cs.isError = !cs.JSonStart && cs.state == 0;
#endregion
break
;
case
'['
:
#region 中括號開始
if
(!cs.JSonStart)
{
cs.arrayStart =
true
;
return
true
;
}
else
if
(cs.JSonStart && cs.state == 1)
{
cs.childrenStart =
true
;
return
true
;
}
#endregion
break
;
case
']'
:
#region 中括號結束
if
(cs.arrayStart && !cs.JSonStart && cs.keyStart <= 2 && cs.valueStart <= 0)
//[{},333]//這樣結束。
{
cs.keyStart = 0;
cs.valueStart = 0;
cs.arrayStart =
false
;
return
true
;
}
#endregion
break
;
case
'"'
:
case
'\''
:
#region 引號
if
(cs.JSonStart || cs.arrayStart)
{
if
(cs.state == 0)
//key階段,有可能是數組["aa",{}]
{
if
(cs.keyStart <= 0)
{
cs.keyStart = (c ==
'"'
? 3 : 2);
return
true
;
}
else
if
((cs.keyStart == 2 && c ==
'\''
) || (cs.keyStart == 3 && c ==
'"'
))
{
if
(!cs.escapeChar)
{
cs.keyStart = -1;
return
true
;
}
else
{
cs.escapeChar =
false
;
}
}
}
else
if
(cs.state == 1 && cs.JSonStart)
//值階段必須是JSon開始了。
{
if
(cs.valueStart <= 0)
{
cs.valueStart = (c ==
'"'
? 3 : 2);
return
true
;
}
else
if
((cs.valueStart == 2 && c ==
'\''
) || (cs.valueStart == 3 && c ==
'"'
))
{
if
(!cs.escapeChar)
{
cs.valueStart = -1;
return
true
;
}
else
{
cs.escapeChar =
false
;
}
}
}
}
#endregion
break
;
case
':'
:
#region 冒號
if
(cs.JSonStart && cs.keyStart < 2 && cs.valueStart < 2 && cs.state == 0)
{
if
(cs.keyStart == 1)
{
cs.keyStart = -1;
}
cs.state = 1;
return
true
;
}
// cs.isError = !cs.JSonStart || (cs.keyStart < 2 && cs.valueStart < 2 && cs.state == 1);
#endregion
break
;
case
','
:
#region 逗號 //["aa",{aa:12,}]
if
(cs.JSonStart)
{
if
(cs.keyStart < 2 && cs.valueStart < 2 && cs.state == 1)
{
cs.state = 0;
cs.keyStart = 0;
cs.valueStart = 0;
//if (cs.valueStart == 1)
//{
// cs.valueStart = 0;
//}
cs.setDicValue =
true
;
return
true
;
}
}
else
if
(cs.arrayStart && cs.keyStart <= 2)
{
cs.keyStart = 0;
//if (cs.keyStart == 1)
//{
// cs.keyStart = -1;
//}
return
true
;
}
#endregion
break
;
case
' '
:
case
'\r'
:
case
'\n'
:
//[ "a",\r\n{} ]
case
'\0'
:
case
'\t'
:
if
(cs.keyStart <= 0 && cs.valueStart <= 0)
//cs.JSonStart &&
{
return
true
;
//跳過空格。
}
break
;
default
:
//值開頭。。
if
(c ==
'\\'
)
//轉義符號
{
if
(cs.escapeChar)
{
cs.escapeChar =
false
;
}
else
{
cs.escapeChar =
true
;
return
true
;
}
}
else
{
cs.escapeChar =
false
;
}
if
(cs.JSonStart || cs.arrayStart)
// JSon 或數組開始了。
{
if
(cs.keyStart <= 0 && cs.state == 0)
{
cs.keyStart = 1;
//無引號的
}
else
if
(cs.valueStart <= 0 && cs.state == 1 && cs.JSonStart)
//只有JSon開始才有值。
{
cs.valueStart = 1;
//無引號的
}
}
break
;
}
return
false
;
}
}
}
四、AjaxResult:前台AJax請求的統一返回結果類
? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92using
System.Web.Script.Serialization;
namespace
Common
{
/// <summary>
/// 前台AJax請求的統一返回結果類
/// </summary>
public
class
AJaxResult
{
private
AJaxResult()
{
}
private
bool
iserror =
false
;
/// <summary>
/// 是否產生錯誤
/// </summary>
public
bool
IsError {
get
{
return
iserror; } }
/// <summary>
/// 錯誤信息,或者成功信息
/// </summary>
public
string
Message {
get
;
set
; }
/// <summary>
/// 成功可能時返回的數據
/// </summary>
public
object
Data {
get
;
set
; }
#region Error
public
static
AJaxResult Error()
{
return
new
AJaxResult()
{
iserror =
true
};
}
public
static
AJaxResult Error(
string
message)
{
return
new
AJaxResult()
{
iserror =
true
,
Message = message
};
}
#endregion
#region Success
public
static
AJaxResult Success()
{
return
new
AJaxResult()
{
iserror =
false
};
}
public
static
AJaxResult Success(
string
message)
{
return
new
AJaxResult()
{
iserror =
false
,
Message = message
};
}
public
static
AJaxResult Success(
object
data)
{
return
new
AJaxResult()
{
iserror =
false
,
Data = data
};
}
public
static
AJaxResult Success(
object
data,
string
message)
{
return
new
AJaxResult()
{
iserror =
false
,
Data = data,
Message = message
};
}
#endregion
/// <summary>
/// 序列化
/// </summary>
/// <returns></returns>
public
override
string
ToString()
{
return
new
JavaScriptSerializer().Serialize(
this
);
}
}
}
常用的一些JSon操作類,留著備用,需要的朋友的直接拿去用吧。