c# - 如何在 C# 中创建 JSON 对象

我需要像这样创建 JSON:

{
  "files": [
    {
      "file_path": "example.txt",
      "content" : "source code \n with multiple lines\n"
    }
  ]
}

但是我的代码(后来序列化成JSON)和上面这个例子不符

var requestBody = new
{
    files = new string[] { snippet.FileName, snippet.Content }
};

有人可以帮我 :) 吗?

编辑:

我的序列化方法:

        protected string serializeToJson( object obj )
        {
            return JsonConvert.SerializeObject( obj, new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() } );
        }

最佳答案

试试看:

using System.Text.Json;

var obj = new
{
    files = new[]
    {
        new
        {
            file_path = "example.txt", 
            content ="source code \n with multiple lines\n" 
        }
    }
};
var json = JsonSerializer.Serialize(obj);
Console.WriteLine(json);

结果:

https://stackoverflow.com/questions/70632236/

相关文章:

rust - 特征的静态工厂方法

xml - 无法解析类 SearchView

c++ - 直接将数组写入参数会在 C++ 中出错

javascript - react-bootstrap-table-toolkit 搜索导入报错

for-loop - For 循环构造转为函数式

bash - 在多个文件中将每第 4 次出现的 char "_"替换为 "@"

c++ - 将全局引用计数资源与原子同步——在这里放宽合适吗?

r - 如何检测 R 中数据框中给定引用变量下方和上方的最接近值?

regex - 在 perl 中使用 foreach 代替 map 和 grep

php - 通过存储在 PHP 字符串中的名称获取枚举值