Home > Software design >  How to create JSON object in C#
How to create JSON object in C#

Time:01-09

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

CodePudding user response:

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

CodePudding user response:

We can make use of the serializeobject to convert into json

string jsonStr = JsonConvert.SerializeObject(obj);

This method will be available in the newtonsoft package

  •  Tags:  
  • Related