Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create JSON object in C#

Tags:

json

c#

I need to create JSON like this:

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

But my code (I serialized it to JSON later) doesn't correspond to this example above

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

Can someone help me :)?

EDIT:

my serialization method:

        protected string serializeToJson( object obj )
        {
            return JsonConvert.SerializeObject( obj, new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() } );
        }
like image 862
Liryk Avatar asked Nov 16 '25 12:11

Liryk


1 Answers

Try That:

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);

Result:

enter image description here

like image 52
Federico Alterio Avatar answered Nov 18 '25 20:11

Federico Alterio