個人不太喜歡XML,於是找了JSON來做配置,JSON雖然有很多引號,但這種key-value的形式,非常符合我的思維,就像是一個蘿卜一個坑。最近在讀寫JSON文件,需要注意兩個問題。
中文亂碼:
直接像讀txt一樣,讀取json文件
//最初的寫法 File.ReadAllText(jsonPath); //防止中文亂碼 File.ReadAllText(jsonPath,Encoding.Default);
寫入格式:
將json轉成字符串寫入json文件時,發現沒有任何換行、空格、Tab,特別不利於查看,尤其是當數據比較多、分級多較復雜的時候
所以,在寫入之前,應當作一下小小的處理,效果如下:
格式化JSON示例:
/// <summary> /// 格式化JSON字符串 /// </summary> /// <param name="str">輸入字符串</param> /// <returns>輸出字符串</returns> public static string FormatJsonStr(string str) { JsonSerializer serializer = new JsonSerializer(); TextReader tr = new StringReader(str); JsonTextReader jtr = new JsonTextReader(tr); object obj = serializer.Deserialize(jtr); if (obj != null) { StringWriter textWriter = new StringWriter(); JsonTextWriter jsonWriter = new JsonTextWriter(textWriter) { Formatting = Formatting.Indented, Indentation = 4, IndentChar = ' ' }; serializer.Serialize(jsonWriter, obj); return textWriter.ToString(); } else { return str; } }
讀寫JSON示例:
/// <summary> /// 讀取JSON文件 /// </summary> /// <param name="jsonPath">json文件路徑</param> /// <returns>json字符串</returns> public static string ReadJsonString(string jsonPath) { if (!File.Exists(jsonPath)) { LogHelper.Error("配置文件不存在:"+ jsonPath); return string.Empty; } return File.ReadAllText(jsonPath,Encoding.Default); } /// <summary> ///讀取JSON文件 /// </summary> /// <param name="jsonPath">json文件路徑</param> /// <returns>JObject對象</returns> public static JObject ReadJsonObj(string jsonPath) { string json = ReadJsonString(jsonPath); JObject jsonObj = null; if (!string.IsNullOrEmpty(json)) { jsonObj=(JObject)JsonConvert.DeserializeObject(json); } return jsonObj; } #region 寫入JSON /// <summary> /// 寫入JSON /// </summary> /// <returns></returns> public static bool Write(string jsonStr,string jsonPath) { try { System.IO.File.WriteAllText(jsonPath, jsonStr, Encoding.Default); return true; } catch (System.Exception ex) { LogHelper.Error("保存結果異常" + ex.Message + ex.StackTrace); return false; } } #endregion
http://www.cnblogs.com/liweis/p/6408967.html