fazlook1
fazlook1

Reputation: 139

How to insert a Boolean variable into a JSON string in C#

Suppose I have the following:

var b = true;
var f = "{ \"templateName\": \"name\", \"Active\": \"" +b + "\"}";

That b value does not work for me :( , I tried different scenario's with no luck.

Upvotes: 1

Views: 4350

Answers (1)

maccettura
maccettura

Reputation: 10819

The proper way of doing this is to work with objects directly. Then you can serialize to whatever format you want (if you want JSON, JSON.NET is what you should use).

For instance, you should have a class that looks something like this:

public class TestClass
{
    public bool Active { get; set; }
    public string TemplateName { get; set; }
}

This is a class that represents your JSON object, but instead of modifying strings and dealing with that headache, we just deal with objects.

In your code you can instantiate and/or modify an instance of that object:

var testObj = new TestClass()
{
    Active = true,
    TemplateName = "SomeName"
};

//changed my mind, I want Active to be false now
testObj.Active = false;

Then with the power of JSON.NET you can serialize this object into JSON:

string jsonString = JsonConvert.SerializeObject(testObj);

Upvotes: 3

Related Questions