Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to create JSON object in 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 :)?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

EDIT:

my serialization method:

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

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading