Home > Blockchain >  How to convert string Variable to json format in C#
How to convert string Variable to json format in C#

Time:05-18

I have a situation where I need to convert and combine 4 string variables into a single json format string. Below is the example I am trying to do.

My 4 Variables:

string SQLServerType = "SQLVM";
string ServerName = "ABCDEF";
string DatabaseName = "WhatEver";
string TriggerStatus = "Disabled";

I would like to combine values of above 4 variables in below json format . Please suggest me how I can achieve this.

{"SQLServerType":"SQLVM","ServerName":"ABCDEF","DatabaseName":"WhatEver","TriggerStatus":"Disabled"}

CodePudding user response:

try this

var json  = JsonConvert.SerializeObject( new Dictionary<string,string> {
        { nameof(SQLServerType), SQLServerType},
        { nameof(ServerName), ServerName},
        { nameof(DatabaseName), DatabaseName},
        { nameof(TriggerStatus), TriggerStatus}
    });

result

{"SQLServerType":"SQLVM","ServerName":"ABCDEF","DatabaseName":"WhatEver","TriggerStatus":"Disabled"}

CodePudding user response:

Thank you @Nick Bailey for giving the link. I figured the answer from comment from @Nick Bailey How to write .NET objects as JSON (serialize)

string SQLServerType = "SQLVM";
        string ServerName = "ABCDEF";
        string DatabaseName = "WhatEver";
        string TriggerStatus = "Disabled";

        string CombinedJsonValue = "";

        var JsonSQLTriggers = new SQLTriggers
        {
            SQLServerType = SQLServerType,
            ServerName = ServerName,
            DatabaseName = DatabaseName,
            TriggerStatus = TriggerStatus
        };

        string jsonString = System.Text.Json.JsonSerializer.Serialize(JsonSQLTriggers);
  • Related