litJson做爲優秀的第三方庫,是解析Json很好的工具。javascript
使用的第三方庫java
添加引用 litJson,以下兩個引用可直接添加System.ServiceModel.Web,System.Runtime.Serialization
using System.Runtime.Serialization; using System.Runtime.Serialization.Json; using LitJson;
解析Json接口,帶簽名的Json接口git
解析固定格式的Json,還有讀取本地Json文件,都很相似。github
{ "library": [{ "materialManufacturer": "11", "regularLabelling": "", "sheetLabelling": "" }, { "materialManufacturer": "fqwfewq", "regularLabelling": "", "sheetLabelling": "" }] }
//一個材料信息,包含以下成員 public class MaterialItem { public static List<MaterialItem> materialList = new List<MaterialItem>(); public string materialManufacturer { get; set; } public string regularLabelling { get; set; } public string sheetLabelling { get; set; } } //材料類 public class Material { public Material() { MaterialItem = new MaterialItem(); } public string matrail { get; set; } public MaterialItem MaterialItem { get; set; } }
/// <summary> /// 主方法 /// </summary> /// <param name="args"></param> public static void Main(string[] args) { //接口url string url = " http://192.168.42.46/Windchill/servlet/Navigation/MaterialLibraryServlet "; //簽名 string restName = "Authorization"; //認證 string restValue = "Basic d2NhZG1pbjp3Y2FkbWlu"; //傳入參數,讀取Json字符串 GetJsonData(url, restName, restValue); }
/// <summary> /// Json解析的方法封裝 /// </summary> /// <param name="tmpUrlI">傳入的接口Url</param> /// <param name="tmpKeyName">簽名</param> /// <param name="tmpKeyValue">認證</param> public static void GetJsonData(string tmpUrlI, string tmpKeyName, string tmpKeyValue) { //獲取請求 HttpWebRequest request = WebRequest.Create(tmpUrlI) as HttpWebRequest; //加入請求頭 request.Headers.Add(tmpKeyName, tmpKeyValue); using (HttpWebResponse response = request.GetResponse() as HttpWebResponse) { //獲取響應數據流 StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8); //得到json字符串 string jsonstr = reader.ReadLine(); JsonData jsonData = JsonMapper.ToObject(jsonstr); if (jsonData != null) { //取library下鍵值字典 JsonData jsonDicList = jsonData["library"]; foreach (JsonData item in jsonDicList) { MaterialItem JO = new MaterialItem(); JO.materialManufacturer = item["materialManufacturer"].ToString(); JO.regularLabelling = item["regularLabelling"].ToString(); JO.sheetLabelling = item["sheetLabelling"].ToString(); MaterialItem.materialList.Add(JO); } } } }
星星之火能夠燎原,今日點滴的付出,是往後的苦盡甘來。莫愁前路漫漫,天下誰人不識君。感謝你閱讀此文稿,也但願你能不吝賜教。推薦比較全面的我的學習網站,但願對你有幫助。json
var normalChild = { nickName : "墨客碼", site : "http://www.cnblogs.com/gss0525/" descTarget : ".net後臺開發者,熱衷分享技術,心懷感恩,深耕不綴。" }