由於項目中需要取網頁上的數據,但是數據時JSON格式的,於是聽同事介紹了一個Newtonsoft.Json.dll文件
具體操作如下:
我的字符串類型為:
string str = "{ 'root':{ 'items': [{'Warehouse': '219410', 'City_St': 'Morrow, GA', 'Bales': '264'},{'Warehouse': '240124', 'City_St': 'Climax, GA', 'Bales': '88'},{'Warehouse': '266405', 'City_St': 'Funston, GA', 'Bales': '176'},{'Warehouse': '297005', 'City_St': 'Meigs, GA', 'Bales': '264'},{'Warehouse': '710527', 'City_St': 'Greenville, SC', 'Bales': '440'}] }} ";
需要循環取出Warehouse的值,這里我們使用了類構造函數
先定義所需要的類類型
public class MyList { public string Warehouse { get; set; } public string City_St { get; set; } } public class Items { public IList<MyList> items { get; set; } } public class Root { public Items root { get; set; } }
然后就可以使用DecodeObject對象轉換了
string str = "{ 'root':{ 'items': [{'Warehouse': '219410', 'City_St': 'Morrow, GA', 'Bales': '264'},{'Warehouse': '240124', 'City_St': 'Climax, GA', 'Bales': '88'},{'Warehouse': '266405', 'City_St': 'Funston, GA', 'Bales': '176'},{'Warehouse': '297005', 'City_St': 'Meigs, GA', 'Bales': '264'},{'Warehouse': '710527', 'City_St': 'Greenville, SC', 'Bales': '440'}] }} "; Root T = Utility.JsonUtility.DecodeObject<Root>(str); for (int i = 0; i < T.root.items.Count; i++) { Response.Write(T.root.items[i].Warehouse+"\n"); }
輸出結果如下圖
完整代碼如下:

1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Web; 5 using System.Web.UI; 6 using System.Web.UI.WebControls; 7 using Newtonsoft.Json; 8 using Newtonsoft.Json.Converters; 9 using System.IO; 10 11 public partial class _Default : System.Web.UI.Page 12 { 13 protected void Page_Load(object sender, EventArgs e) 14 { 15 string str = "{ 'root':{ 'items': [{'Warehouse': '219410', 'City_St': 'Morrow, GA', 'Bales': '264'},{'Warehouse': '240124', 'City_St': 'Climax, GA', 'Bales': '88'},{'Warehouse': '266405', 'City_St': 'Funston, GA', 'Bales': '176'},{'Warehouse': '297005', 'City_St': 'Meigs, GA', 'Bales': '264'},{'Warehouse': '710527', 'City_St': 'Greenville, SC', 'Bales': '440'}] }} "; 16 Root T = Utility.JsonUtility.DecodeObject<Root>(str); 17 for (int i = 0; i < T.root.items.Count; i++) 18 { 19 Response.Write(T.root.items[i].Warehouse+"\n"); 20 } 21 } 22 23 public class MyList 24 { 25 public string Warehouse { get; set; } 26 public string City_St { get; set; } 27 } 28 public class Items 29 { 30 public IList<MyList> items { get; set; } 31 } 32 public class Root 33 { 34 public Items root { get; set; } 35 } 36 37 private static string StringFormat(string str, Type type) 38 { 39 if (type == typeof(string)) 40 { 41 str = String2Json(str); 42 str = "\"" + str + "\""; 43 } 44 else if (type == typeof(DateTime)) 45 { 46 str = "\"" + str + "\""; 47 } 48 else if (type == typeof(bool)) 49 { 50 str = str.ToLower(); 51 } 52 return str; 53 } 54 55 }
注:項目中的Newtonsoft是有3個版本的.NET2.0 、3.5、 4.0 要引用對應的版本才能找到名稱空間;
Utility.cs完整代碼如下:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Newtonsoft.Json.Converters; using Newtonsoft.Json; using System.IO; /// <summary> ///JsonUtility 的摘要說明 /// </summary> public class Utility { /// <summary> /// Json工具類 /// </summary> public static class JsonUtility { /// <summary> /// 添加時間轉換器 /// </summary> /// <param name="serializer"></param> private static void AddIsoDateTimeConverter(JsonSerializer serializer) { IsoDateTimeConverter idtc = new IsoDateTimeConverter(); //定義時間轉化格式 idtc.DateTimeFormat = "yyyy-MM-dd HH:mm:ss"; //idtc.DateTimeFormat = "yyyy-MM-dd"; serializer.Converters.Add(idtc); } /// <summary> /// Json轉換配置 /// </summary> /// <param name="serializer"></param> private static void SerializerSetting(JsonSerializer serializer) { serializer.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; //serializer.NullValueHandling = NullValueHandling.Ignore; //serializer.MissingMemberHandling = MissingMemberHandling.Ignore; //serializer.DefaultValueHandling = DefaultValueHandling.Ignore; } /// <summary> /// 返回結果消息編碼 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="sucess"></param> /// <param name="message"></param> /// <param name="exMessage"></param> /// <param name="data"></param> /// <returns></returns> public static string ReturnMessage(bool sucess, int total, string message, string exMessage, string data) { message = message.Replace("'", "").Replace("\"", "").Replace("<", "").Replace(">", ""); exMessage = exMessage.Replace("'", "").Replace("\"", "").Replace("<", "").Replace(">", ""); return string.Format("{{success:{0},total:{1},data:{2},message:\"{3}\",exMessage:\"{4}\"}}", sucess.ToString().ToLower(), total, data, message, exMessage); } /// <summary> /// 返回失敗信息 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="message"></param> /// <param name="exMessage"></param> /// <returns></returns> public static string ReturnFailureMessage(string message, string exMessage) { return ReturnMessage(false, 0, message, exMessage, "[]"); } /// <summary> /// 返回失敗信息 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="message"></param> /// <param name="exMessage"></param> /// <returns></returns> public static string ReturnFailureMessageTouch(string message, string exMessage) { return "{\"success\":\"false\",\"msg\":\"" + exMessage + "\"}"; } /// <summary> /// 返回成功信息 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="total"></param> /// <param name="message"></param> /// <param name="exMessage"></param> /// <param name="objList"></param> /// <returns></returns> public static string ReturnSuccessMessage<T>(int total, string message, string exMessage, List<T> objList) { string data = ListToJson<T>(objList); return ReturnMessage(true, total, message, exMessage, data); } public static string ReturnSuccessMessageTouch<T>(T obj) { string data = ObjectToJson<T>(obj); return data; } /// <summary> /// 返回成功信息 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="total"></param> /// <param name="message"></param> /// <param name="exMessage"></param> /// <param name="objList"></param> /// <returns></returns> public static string ReturnSuccessMessage(string message, string exMessage) { return ReturnMessage(true, 0, message, exMessage, "[]"); } /// <summary> /// 返回成功信息 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="total"></param> /// <param name="message"></param> /// <param name="exMessage"></param> /// <param name="objList"></param> /// <returns></returns> public static string ReturnSuccessMessageTouch(string message, string exMessage) { return "{\"success\":\"true\",\"msg\":\"" + message + "\"}"; } /// <summary> /// 返回成功信息 /// </summary> /// <param name="message"></param> /// <param name="exMessage"></param> /// <param name="data">JSON 對象</param> /// <returns></returns> public static string ReturnSuccessMessage(string message, string exMessage, string data) { return ReturnMessage(true, 0, message, exMessage, "[" + data + "]"); } /// <summary> /// 返回成功消息 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="total"></param> /// <param name="message"></param> /// <param name="exMessage"></param> /// <param name="obj"></param> /// <returns></returns> public static string ReturnSuccessMessage<T>(int total, string message, string exMessage, T obj) { string data = ObjectToJson<T>(obj); return ReturnMessage(true, total, message, exMessage, data); } /// <summary> /// 把對象列表編碼為Json數據 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="objList"></param> /// <returns></returns> public static string ListToJson<T>(List<T> objList) { JsonSerializer serializer = new JsonSerializer(); SerializerSetting(serializer); AddIsoDateTimeConverter(serializer); using (TextWriter sw = new StringWriter()) using (JsonWriter writer = new JsonTextWriter(sw)) { serializer.Serialize(writer, objList); return sw.ToString(); } } /// <summary> /// 把一個對象編碼為Json數據 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="obj"></param> /// <returns></returns> public static string ObjectToJson<T>(T obj) { JsonSerializer serializer = new JsonSerializer(); SerializerSetting(serializer); AddIsoDateTimeConverter(serializer); using (TextWriter sw = new StringWriter()) using (JsonWriter writer = new JsonTextWriter(sw)) { serializer.Serialize(writer, obj); return sw.ToString(); } } /// <summary> /// 根據傳入的Json數據,解碼為對象(一個) /// </summary> /// <typeparam name="T"></typeparam> /// <param name="data"></param> /// <returns></returns> public static T DecodeObject<T>(string data) { JsonSerializer serializer = new JsonSerializer(); serializer.MissingMemberHandling = MissingMemberHandling.Ignore; AddIsoDateTimeConverter(serializer); StringReader sr = new StringReader(data); return (T)serializer.Deserialize(sr, typeof(T)); } /// <summary> /// 功能同DecodeObject /// </summary> /// <typeparam name="T"></typeparam> /// <param name="data"></param> /// <returns></returns> public static List<T> DecodeObjectList<T>(string data) { JsonSerializer serializer = new JsonSerializer(); serializer.MissingMemberHandling = MissingMemberHandling.Ignore; AddIsoDateTimeConverter(serializer); StringReader sr = new StringReader(data); return (List<T>)serializer.Deserialize(sr, typeof(List<T>)); } public static string EncodeAjaxResponseJson(string jsonString, string callback) { String responseString = ""; //判斷是否jsonp調用 if (!String.IsNullOrEmpty(callback)) { //jsonp調用,需要封裝回調函數,並返回 responseString = callback + "(" + jsonString + ")"; } else { //普通ajax調用,直接返回Json數據 responseString = jsonString; } return responseString; } public static string ExtGridSortInfo(string property, string direction) { return string.Format("[{{\"property\":\"{0}\",\"direction\":\"{1}\"}}]", property, direction); } } }