本文著重介紹下JSON數(shù)據(jù)格式的相關(guān)內(nèi)容說明,隨著JSON的不斷發(fā)展,編程的技巧也出現(xiàn)了不一樣的形式,對(duì)一些輕量級(jí)的數(shù)據(jù)交換格式進(jìn)行編寫時(shí),需要注意一些問題,比如輕量級(jí)的數(shù)據(jù)交換格式的問題。
本次工作內(nèi)容是要將以下數(shù)據(jù)解析成.Net可以使用的數(shù)據(jù),返回的數(shù)據(jù)除了header,其他的都是可變的,也就是說結(jié)構(gòu)不是固定的。完全由用戶選擇,所以選擇了生成DataTable。
SON數(shù)據(jù)格式如下:
- using System;
-
- using System.Collections.Generic;
-
- using System.Text;
-
- using System.Data;
-
- using System.Web.Script.Serialization;
-
-
-
- namespace Tencent.Itil.Cmsi.Common
-
- {
-
- public class GeneralSearchResult
-
- {
-
- public Header header = new Header();
-
- private DataTable fieldDefine = new DataTable();
-
- /// <summary>
-
- /// 返回的數(shù)據(jù)結(jié)構(gòu)定義,無數(shù)據(jù)
-
- /// </summary>
-
- public DataTable FieldDefine
-
- {
-
- get { return fieldDefine; }
-
- set { fieldDefine = value; }
-
- }
-
-
-
- private DataTable retrunData = new DataTable();
-
- /// <summary>
-
- /// 返回的數(shù)據(jù),格式為DataTable,結(jié)構(gòu)和FieldDefine中的結(jié)構(gòu)一樣
-
- /// </summary>
-
- public DataTable RetrunData
-
- {
-
- get { return retrunData; }
-
- set { retrunData = value; }
-
- }
-
-
-
- /// <summary>
-
- /// 將json數(shù)據(jù)轉(zhuǎn)換為定義好的對(duì)象,數(shù)據(jù)轉(zhuǎn)換為DataTable
-
- /// </summary>
-
- /// <param name="jsonText"></param>
-
- /// <returns></returns>
-
- public static GeneralSearchResult GetTransformData(string jsonText)
-
- {
-
- GeneralSearchResult gsr = new GeneralSearchResult();
-
-
-
- JavaScriptSerializer s = new JavaScriptSerializer();
-
- Dictionary<string, object> JsonData = (Dictionary<string, object>)s.DeserializeObject(jsonText);
-
- Dictionary<string, object> dataSet = (Dictionary<string, object>)JsonData["dataSet"];
-
- Dictionary<string, object> header = (Dictionary<string, object>)dataSet["header"];
-
- Dictionary<string, object> fieldDefine = (Dictionary<string, object>)dataSet["header"];
-
- Dictionary<string, object> data = (Dictionary<string, object>)dataSet["data"];
-
- object[] rows = (object[])data["row"];
-
- gsr.header.Version = header["version"].ToString();
-
- gsr.header.ErrorInfo = header["errorInfo"].ToString();
-
- gsr.header.ReturnCode = header["returnCode"].ToString();
-
- gsr.header.ReturnRows = Convert.ToInt16(header["returnRows"]);
-
- gsr.header.TotalRows = Convert.ToInt16(header["totalRows"]);
-
-
-
- Dictionary<string, object> dicFieldDefine = (Dictionary<string, object>)dataSet["fieldDefine"];
-
- foreach (KeyValuePair<string, object> ss in dicFieldDefine)
-
- {
-
-
-
- gsr.FieldDefine.Columns.Add(ss.Key, typeof(string));
-
-
-
- }
JSON數(shù)據(jù)格式使用方法:
- GeneralSearchResult gsr = new GeneralSearchResult();
- gsr = GeneralSearchResult.GetTransformData(text);
本文出自:億恩科技【mszdt.com】
服務(wù)器租用/服務(wù)器托管中國(guó)五強(qiáng)!虛擬主機(jī)域名注冊(cè)頂級(jí)提供商!15年品質(zhì)保障!--億恩科技[ENKJ.COM]
|