Jayson Ragasa
Jayson Ragasa

Reputation: 1029

Using JSON.NET to add a boolean property

I have this JSON data

{
    "extensions": {
        "settings" : {
            "extension1": {
                "property1": "value 1",
                "property2": "value 2"
            }
        }
    }
}

my goal is to add a new boolean property using JSON.NET to look like this

{
    "extensions": {
        "settings" : {
            "extension1": {
                "property1": "value 1",
                "property2": "value 2",
                "bool_property": true
            }
        }
    }
}

I only have this code and I'm stuck with AddAfterSelf and AddBeforeSelf

string pref = "path_of_the_preferences_file";
string _pref = string.empty;
using (StreamReader reader = new StreamReader(pref, Encoding.UTF8))
{
    _pref = reader.ReadToEnd();
}

// REFORMAT JSON.DATA
JObject json = JObject.Parse(_pref);
var extension1 = json["extensions"]["settings"]["extension1"];

How do I insert the new boolean property "bool_property" ?

Thanks

Upvotes: 4

Views: 10772

Answers (3)

Jayson Ragasa
Jayson Ragasa

Reputation: 1029

I got it

string pref = "path_of_the_preferences_file";
string _pref = string.empty;
using (StreamReader reader = new StreamReader(pref, Encoding.UTF8))
{
    _pref = reader.ReadToEnd();
}

// REFORMAT JSON.DATA
JObject json = JObject.Parse(_pref);
var extension1 = json["extensions"]["settings"]["extension1"];

var a = extension1.Children();
JProperty cond_it = null;

foreach (var b in a)
{
    if (b.ToString().ToLower().Contains("cond_it"))
    {
        cond_it = (JProperty)b;

        break;
    }
}

if (cond_it != null)
{
    var b = cond_it.Value.SelectToken("location").Parent;
    b.AddAfterSelf(new JProperty("blacklist", true));
}

Upvotes: 0

Jeff Mercado
Jeff Mercado

Reputation: 134521

A JObject is essentially a dictionary. Just get a reference to the object you wish to add the property to and add it.

var propertyName = "bool_property";
var value = true;

var obj = JObject.Parse(json);
var extension1 = obj.SelectToken("extensions.settings.extension1") as JObject;
if (extension1 != null)
{
    extension1[propertyName] = value;
}

If you're targeting .NET 4 and up, you know the structure of the json and the name of the property you wish to add, you can use dynamic here.

var value = true;

dynamic obj = JObject.Parse(json);
obj.extensions.settings.extension1.bool_value = value;

You can even mix and match.

var propertyName = "bool_property";
var value = true;

dynamic obj = JObject.Parse(json);
obj.extensions.settings.extension1[propertyName] = value;

Upvotes: 7

fjdumont
fjdumont

Reputation: 1537

Deserialize your JSON, add a property and serialize it back into a string.

dynamic sourceJson = JsonConvert.DeserializeObject(json, typeof(object));
sourceJson.extensions.settings.extension1.bool_property = false;
var modifiedJson = JsonConvert.SerializeObject(sourceJson, Formatting.Indented);

Upvotes: 4

Related Questions