json_file_operation.cs 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using Newtonsoft.Json;
  7. using Newtonsoft.Json.Linq;
  8. using System.Windows.Forms;
  9. namespace tool
  10. {
  11. //json文件操作类 暂时只有读取字段功能 后续可拓展
  12. class json_file_operation : Singleton<json_file_operation>
  13. {
  14. private json_file_operation()
  15. {
  16. }
  17. //初始化--传入json文件路径
  18. public void json_file_operation_init(string jsonPath)
  19. {
  20. this.jsonPath = jsonPath;
  21. //string jsonArrayText1 = "[{'communication_bind':'127.0.0.1'} ,{'communication_bind':'127.0.0.2'} ]";
  22. //JArray ja = (JArray)JsonConvert.DeserializeObject(jsonArrayText1);
  23. //string ja1a = ja[1]["communication_bind"].ToString();
  24. //Console.WriteLine(ja1a);
  25. }
  26. //读取json文件指定字段 返回string
  27. public JArray read_json_jarray(string key)
  28. {
  29. try
  30. {
  31. using (System.IO.StreamReader file = System.IO.File.OpenText(jsonPath))
  32. {
  33. try
  34. {
  35. using (JsonTextReader reader = new JsonTextReader(file))
  36. {
  37. JObject o = (JObject)JToken.ReadFrom(reader);
  38. string jsonArrayText1 = o[key].ToString();
  39. JArray ja = (JArray)JsonConvert.DeserializeObject(jsonArrayText1);
  40. return ja;
  41. }
  42. }
  43. catch (Exception ex)
  44. {
  45. string tip = key + "字段不存在!";
  46. MessageBox.Show(tip);
  47. return null;
  48. }
  49. }
  50. }
  51. catch (Exception ex)
  52. {
  53. string tip = jsonPath + " 文件路径不存在!";
  54. MessageBox.Show(tip);
  55. return null;
  56. }
  57. }
  58. //读取json文件指定字段 返回string
  59. public string read_json_string(string key)
  60. {
  61. try
  62. {
  63. using (System.IO.StreamReader file = System.IO.File.OpenText(jsonPath))
  64. {
  65. try
  66. {
  67. using (JsonTextReader reader = new JsonTextReader(file))
  68. {
  69. JObject o = (JObject)JToken.ReadFrom(reader);
  70. var value = o[key].ToString();
  71. return value;
  72. }
  73. }
  74. catch (Exception ex)
  75. {
  76. string tip = key + "字段不存在!";
  77. MessageBox.Show(tip);
  78. return null;
  79. }
  80. }
  81. }
  82. catch (Exception ex)
  83. {
  84. string tip = jsonPath + " 文件路径不存在!";
  85. MessageBox.Show(tip);
  86. return null;
  87. }
  88. }
  89. protected string jsonPath;
  90. }
  91. }