什麼是JSON:編程
須要在項目中進行引用:Newtonsoft.Json.dll 並添加命名空間:using Newtonsoft.Json; 序列化函數:JsonConvert.SerializeObject(object value),它有個重載方法JsonConvert.SerializeObject(object value, params JsonConverter[] converters)。 反序列化函數:JsonConvert.DeserializeObject(string value, Type type) 它有個重載方法JsonConvert.DeserializeObject(string value, Type type, params JsonConverter[] converters)
注意:實體類必須public類型json
/// <summary> /// 獲取成功返回的JSON實體類 /// </summary> public class InfoReq { /// <summary> /// 返回消息,200成功 /// </summary> public string msg; /// <summary> /// 返回的數據 /// </summary> public string data; /// <summary> /// 返回時間 /// </summary> public string DateTimes = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss"); } InfoReq infoReq = new InfoReq(); infoReq.msg = "200"; infoReq.data = "daxi"; //infoReq.DateTimes ="2019-11-25 12:59:22"; string result = JsonConvert.SerializeObject(infoReq);
string jsonStr = "{\"msg\":\"404\",\"data\":\"not\",\"DateTimes \":\"2019-12-10 15:22:32\"}"; InfoReq infoReqs = (InfoReq)JsonConvert.DeserializeObject(jsonStr,typeof(InfoReq));