本文著重介紹下JSON數據格式的相關內容說明,隨著JSON的不斷發展,編程的技巧也出現了不一樣的形式,對一些輕量級的數據交換格式進行編寫時,需要注意一些問題,比如輕量級的數據交換格式的問題。
本次工作內容是要將以下數據解析成.Net可以使用的數據,返回的數據除了header,其他的都是可變的,也就是說結構不是固定的。完全由用戶選擇,所以選擇了生成DataTable。
SON數據格式如下:
- 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>
- /// 返回的數據結構定義,無數據
- /// </summary>
- public DataTable FIEldDefine
- {
- get { return fIEldDefine; }
- set { fIEldDefine = value; }
- }
- private DataTable retrunData = new DataTable();
- /// <summary>
- /// 返回的數據,格式為DataTable,結構和FIEldDefine中的結構一樣
- /// </summary>
- public DataTable RetrunData
- {
- get { return retrunData; }
- set { retrunData = value; }
- }
- /// <summary>
- /// 將JSon數據轉換為定義好的對象,數據轉換為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數據格式使用方法:
- GeneralSearchResult gsr = new GeneralSearchResult();
- gsr = GeneralSearchResult.GetTransformData(text);