Bram
Bram

Reputation: 739

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

Upvotes: 0

Views: 562

Answers (2)

Charlieface
Charlieface

Reputation: 71578

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

Upvotes: 1

Roman Marusyk
Roman Marusyk

Reputation: 24589

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

Upvotes: 4

Related Questions