How to serialize to JSON without using an object

I want to serialize my variables to JSON so I can POST the JSON to an external API. I'd rather not make an separate model just to serialize these values.

It's not possible to use a Dictionary because the structure is not default like "var" : "input" , I'm struggling because one of the fields is structured like: "entryType" : { "name" : "Monitoring" }.

Does anyone have an suggestion what's the best approach here?

var number = "MLD2101 0107";
var briefDescription = "Test";
var EntryType = "Monitoring";

Im trying to serialize the variables above into the following JSON:

  "number": "MLD2101 0107",
  "briefDescription": "Test",
  "entryType" : { "name" : "Monitoring" },

Edit

I Found the following solution from NewtonSoft:

JObject jsonObject =
    new JObject(
        new JProperty("number", number),
        new JProperty("briefDescription", briefDescription),
        new JProperty("entryType", 
            new JObject("name" , entryType))
    );

2 answers

  • answered 2021-01-18 22:34 Roman Marusyk

    If you're using Newtonsoft JSON.NET then try this approach with an anonymous object

    string json = JsonConvert.SerializeObject(new
        {
           number,
           briefDescription,
           entryType = new { name = EntryType }
        });
    

    for System.Text.Json:

    string json = JsonSerializer.Serialize(new
         {
            number,
            briefDescription,
            entryType = new { name = EntryType }
         });
    

  • answered 2021-01-18 22:42 Charlieface

    You can actually nest Dictionaries, like so:

    var json = JsonConvert.SerializeObject(
        new Dictionary<string, object> {
            {"number", "MLD2101 0107"},
            {"briefDescription", "Test"},
            {"entryType", new Dictionary<string, object> {
                { "name", "Monitoring" }
            }
        });