如何序列化 JSON 保存到变量中并在控制台中显示 json 字符串

How to serialize JSON save into variable and display json string in console

这是我的代码

我正在将 JSON 保存到文件中:

public static void Save(string path, Workspace workspace)
        {
            using (StreamWriter file = File.CreateText(path))
            {
                try
                {
                    JsonSerializer serializer = new JsonSerializer();
                    serializer.ContractResolver = new CamelCasePropertyNamesContractResolver();
                    serializer.Serialize(file, workspace);
                }
                catch (Exception)
                {
                    Console.WriteLine("Problem saving to file");
                }
            }
        }

Program.cs

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

因此整个代码生成 json 文件到我的工作区 class 并将此文件保存到我的光盘中。

我有控制台应用程序,我需要生成 json(不保存到文件)但将其保存到变量中并显示 json 字符串内容在控制台中。

您可以使用库 Newtonsoft.Json 并调用 .SerializeObject() 函数

using Newtonsoft.Json; // Import the following namespace
// Serialize the workspace object in the Save method just like this
string workspaceAsJson = JsonConvert.SerializeObject(workspace);

如果你想使用 NewtonSoft 你也可以使用 JSON 东西 built-in 到 Netcore。

var workspaceAsJson = System.Text.Json.JsonSerializer.Serialize(workspace);

Console.WriteLine(workspaceAsJson);