如何读取 JSON 文件并在控制台应用程序中显示它 C#

How to read JSON file and display it in console app c#

我有将数据保存到 JSON 文件的工作方法。 现在我需要读取该文件并在控制台中显示。

我错过了什么?

下面是我的代码

我的阅读方法:

 public static void Read(string path, Workspace workspace)
        {
            using (StreamReader file = new StreamReader(path))
            {
                try
                {
                    string json = file.ReadToEnd();

                    var serializerSettings = new JsonSerializerSettings
                    {
                        ContractResolver = new CamelCasePropertyNamesContractResolver()
                    };

                    var workspace1 = JsonConvert.DeserializeObject<Workspace>(json, serializerSettings);
                    workspace = workspace1;
 
                }
                catch (Exception)
                {
                    Console.WriteLine("Problem reading file");
                }
            }
        }

在program.cs

            Serializer.Save("C:\Users\user\Desktop\test.json", workspace);

            Serializer.Read("C:\Users\user\Desktop\test.json", workspace);


            Console.ReadKey();

左边是我的 json 文件,右边是我想在控制台中显示的内容。

您缺少关键字 ref:

public static void Read(string path, ref Workspace workspace)

就是说,您不应该使用它。使函数 return 成为 Workspace.

更正如下

public static Workspace Read(string path)
{
    using (StreamReader file = new StreamReader(path))
    {
        try
        {
            string json = file.ReadToEnd();

            var serializerSettings = new JsonSerializerSettings
            {
                ContractResolver = new CamelCasePropertyNamesContractResolver()
            };

            return JsonConvert.DeserializeObject<Workspace>(json, serializerSettings);
        }
        catch (Exception)
        {
            Console.WriteLine("Problem reading file");

            return null;
        }
    }
}

static void Main(string[] args)
{
    var data = Read("D:\workspace.json");

    Console.WriteLine("Hello World!");
}