C#读取,写入,保存json

前提要引入:using Newtonsoft.Json;

读取:

        public static object Read_json(string Path)
        {
            Object obji = JsonConvert.DeserializeObject<Object>(File.ReadAllText(Path));  // 尖括号<>中填入对象的类名 
            return obji;
        }

写入:

 1  List<JsonModel> json_data = new List<JsonModel>();
 2             foreach (var method in Value_methods)
 3             {//构建字典
 4                 Console.WriteLine("*************************");
 5                 Console.WriteLine(method.Identifier.ValueText);
 6                 //Console.WriteLine(method.ParameterList);
 7                 //Console.WriteLine(method.ToFullString());
 8                 SyntaxTree tree_method = CSharpSyntaxTree.ParseText(method.ToFullString());
 9                 CompilationUnitSyntax root_method = tree_method.GetCompilationUnitRoot();
10                 var nodes = root_method.DescendantNodes()
11                             .OfType<MemberAccessExpressionSyntax>();                
12                 foreach (var node in nodes.Distinct())
13                 {
14                     JsonModel JsonValue = new JsonModel();
15                     JsonValue.Source = method.Identifier.ValueText;
16                     JsonValue.Target = node + "";
17                     json_data.Add(JsonValue);
18                 }
19             }
20             string json = JsonConvert.SerializeObject(json_data);

存储:

        public static Boolean Save_json(string Path,string value)
        {
            if (!File.Exists(Path))  // 判断是否已有相同文件 
            {
                FileStream fs1 = new FileStream(Path, FileMode.Create, FileAccess.ReadWrite);
                fs1.Close();
            }
            File.WriteAllText(Path, value);
            return true;
        }

 

posted @ 2021-07-17 16:36  博二爷  阅读(3186)  评论(0编辑  收藏  举报