1. 程式人生 > >C# Json解析Json = "{\"EX_RETURN\":[{\"MATNR\":\"test\"}] }";

C# Json解析Json = "{\"EX_RETURN\":[{\"MATNR\":\"test\"}] }";

string jtext = "{\"jiangsu\":[{\"wuxi\":\"無錫\"},{\"suzhou\":\"蘇州\"},{\"nanjing\":\"南京\"}] }";

//解析Json物件 JObject a = (JObject)JsonConvert.DeserializeObject(jtext); string a1 = a["jiangsu"][2]["nanjing"].ToString(); //對Json資料進行解析 Console.WriteLine(a1); Console.ReadLine();

//解析Json陣列 string a4 = a["jiangsu"].ToString(); //從Json資料中取一個數組出來 JArray a2 = (JArray)JsonConvert.DeserializeObject(a4); string a3 = a2[2]["nanjing"].ToString(); //對Json資料進行解 Console.WriteLine(a3); Console.ReadLine();--------------------- 案例H3BPM主資料同步:

using System;using System.Collections.Generic;using System.Data;using System.IO;using System.Linq;using System.Net;using System.Security.Cryptography;using System.Text;using System.Web;using System.Web.Services;using System.Xml;using Newtonsoft.Json;using OThinker.H3.BizBus.BizService;using OThinker.H3;using OThinker.H3.Data;using OThinker.H3.WorkSheet;using System.Collections;using System.Reflection;using System.Web.Script.Serialization;using Newtonsoft.Json.Linq;using log4net;

namespace OThinker.H3.Portal{ /// <summary> /// MaterialMasterDataSynchro 的摘要說明 /// </summary> /// <summary> /// BPMFsscWebService 的摘要說明 /// </summary> [WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] // 若要允許使用 ASP.NET AJAX 從指令碼中呼叫此 Web 服務,請取消註釋以下行。 // [System.Web.Script.Services.ScriptService] public class MaterialMasterDataSynchro : IBaseJob { public MaterialMasterDataSynchro() { // // TODO: 在此處新增建構函式邏輯 // } private readonly ILog _logger = LogManager.GetLogger(typeof(JobSyncSapSupplier));

public override void JobMethod(ZD_SyncTaskConfig plan) { GetMaterialInfo(plan.SyncSuccessBeginTime.ToString("yyyy.MM.dd")); }

[WebMethod] public string HelloWorld() { return "Hello World"; } private IEngine _Engine = null; /// <summary> /// 流程引擎的介面,該介面會比this.Engine的方式更快,因為其中使用了快取 /// </summary> public IEngine Engine { get { if (OThinker.H3.WorkSheet.AppConfig.ConnectionMode == ConnectionStringParser.ConnectionMode.Mono) { return OThinker.H3.WorkSheet.AppUtility.Engine; } return _Engine; } set { _Engine = value; } }

public string AdminId { get { return OThinker.H3.WorkSheet.AppUtility.Engine.Organization.GetUnitByCode("Administrator").ObjectID; } } ReturnResult result;

/// <summary> /// SAP獲得物料主資料資訊 /// string Json = "{\"EX_RETURN\":[{\"MATNR\":\"test\"}] }"; /// </summary> [WebMethod(Description = "獲取SAP物料主資料資訊")] public string GetMaterialInfo(string lastSuccessDate) {

DataTable dataTable = new DataTable(); //例項化 string Json = string.Empty; try { Dictionary<string, object> dic = new Dictionary<string, object>(); //List<Item> list = new List<Item>(); //dic.Add("MT_MM_WLZSJ.IM_INPUT", ""); Json = GetInterfaceDataService.ExecuteBizNonQueryToJson("MaterialMasterDataInterface", "SI_MM_WLZSJ_OS", dic); JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer(); javaScriptSerializer.MaxJsonLength = Int32.MaxValue; //取得最大數值 JObject jObject = (JObject)JsonConvert.DeserializeObject(Json); //此處放json資料 string ex_return = jObject["EX_RETURN"].ToString(); ArrayList arrayList = javaScriptSerializer.Deserialize<ArrayList>(ex_return); foreach (Dictionary<string, object> dictionary in arrayList) { if (dataTable.Columns.Count == 0) { foreach (string current in dictionary.Keys) { dataTable.Columns.Add(current, dictionary[current].GetType()); } } DataRow dataRow = dataTable.NewRow(); foreach (string current in dictionary.Keys) { dataRow[current] = dictionary[current]; } dataTable.Rows.Add(dataRow); //迴圈新增行到DataTable中 } } catch (Exception ex) { result = new ReturnResult(false, "SAP主資料增量同步失敗!" + ex); } if (dataTable.Rows.Count > 0) { StringBuilder sb = new StringBuilder(); string sql = string.Format(@"select * from Tab_SAPMaterialMasterData"); DataTable SelectDt = AppUtility.Engine.Query.QueryTable(sql); if (SelectDt.Rows.Count > 0) { string DeleteSql = string.Format(@"delete from Tab_SAPMaterialMasterData"); DataTable DeleteDt = AppUtility.Engine.Query.QueryTable(DeleteSql); } for (int j = 0; j < dataTable.Rows.Count; j++) { string InsertSql = string.Format(@"INSERT Tab_SAPMaterialMasterData(MATNR,MAKTX,BWKEY,VPRSV,BKLAS,MTART,MEINS,MATKL,BESKZ) VALUES('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}')", dataTable.Rows[j]["MATNR"].ToString(), dataTable.Rows[j]["MAKTX"].ToString(), dataTable.Rows[j]["BWKEY"].ToString(), dataTable.Rows[j]["VPRSV"].ToString(), dataTable.Rows[j]["BKLAS"].ToString(), dataTable.Rows[j]["MTART"].ToString(), dataTable.Rows[j]["MEINS"].ToString(), dataTable.Rows[j]["MATKL"].ToString(), dataTable.Rows[j]["BESKZ"].ToString()); sb.Append(InsertSql); } OThinker.H3.WorkSheet.AppUtility.Engine.Query.CommandFactory.CreateCommand().ExecuteNonQuery(sb.ToString()); result = new ReturnResult(true, "SAP主資料增量同步成功!"); } else { result = new ReturnResult(false, "SAP主資料增量同步失敗!"); }

return result.ToString(); } public class Item { public string WERKS { get; set; } } /// <summary> /// 將泛型集合類轉換成DataTable /// </summary> /// <typeparam name="T">集合項型別</typeparam> /// <param name="list">集合</param> /// <param name="propertyName">需要返回的列的列名</param> public static DataTable ToDataTable<T>(IList<T> list, params string[] propertyName) { List<string> propertyNameList = new List<string>(); if (propertyName != null) propertyNameList.AddRange(propertyName);

DataTable result = new DataTable(); if (list.Count > 0) { PropertyInfo[] propertys = list[0].GetType().GetProperties(); foreach (PropertyInfo pi in propertys) { if (propertyNameList.Count == 0) { result.Columns.Add(pi.Name, pi.PropertyType); } else { if (propertyNameList.Contains(pi.Name)) result.Columns.Add(pi.Name, pi.PropertyType); } }

for (int i = 0; i < list.Count; i++) { ArrayList tempList = new ArrayList(); foreach (PropertyInfo pi in propertys) { if (propertyNameList.Count == 0) { object obj = pi.GetValue(list[i], null); tempList.Add(obj); } else { if (propertyNameList.Contains(pi.Name)) { object obj = pi.GetValue(list[i], null); tempList.Add(obj); } } } object[] array = tempList.ToArray(); result.LoadDataRow(array, true); } } return result; }

public class ReturnResult { /// <summary> /// 訊息類建構函式 /// </summary> /// <param name="success"></param> /// <param name="message"></param> public ReturnResult(bool success, string message, string instanceId) { this.Success = success; this.Message = message; }

/// <summary> /// 訊息類建構函式 /// </summary> /// <param name="success"></param> /// <param name="message"></param> public ReturnResult(bool success, string message) : this(success, message, string.Empty) {

}

public ReturnResult() { }

private bool success = false; /// <summary> /// 是否成功 /// </summary> public bool Success { get { return success; } set { success = value; } } private string message = string.Empty; /// <summary> /// 獲取或設定系統返回訊息 /// </summary> public string Message { get { return message; } set { this.message = value; } } } }}