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

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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

Method 2

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


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x