3

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() } );
        }
3
  • Where's the code that does the de/serialization? Commented Jan 8, 2022 at 12:22
  • You don't have an array of string, you have an array of something that has two string properties - file_path and content Commented Jan 8, 2022 at 12:23
  • @Enigmativity i put it in my question Commented Jan 8, 2022 at 12:24

2 Answers 2

14

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

Sign up to request clarification or add additional context in comments.

1 Comment

work perfect for me, thanks :)
0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.