首页 > 编程 > .NET > 正文

asp.net(C#)解析Json的类代码

2024-07-10 12:42:44
字体:
来源:转载
供稿:网友
本次工作内容是要将以下数据解析成.Net可以使用的数据,返回的数据除了header,其他的都是可变的,也就是说结构不是固定的。完全由用户选择,所以选择了生成DataTable。
Json数据格式如下:
代码如下:
{"dataSet":{
"header":{
"returnCode":"0",
"errorInfo":"HTTP请求错误",
"version":"V1.0R010",
"totalRows":"2000",
"returnRows":"20"
},
"fieldDefine":{
"assetId":"string",
"serverIdcId":"int",
"inputTime":"datetime"
},
"data":{"row":[
{
"AssetId":"TCNS2006888",
"ServerIdcId":"1",
"InputTime":"2008-12-12"
},
{
"AssetId":"TCNS2006889",
"ServerIdcId":"2",
"InputTime":"2008-1-1"
}
]}
}
}

解析的类:
代码如下:
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)
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表