Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using JSON.NET to add a boolean property

Tags:

json

c#

json.net

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

like image 734
Jayson Ragasa Avatar asked Dec 21 '22 04:12

Jayson Ragasa


1 Answers

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;
like image 136
Jeff Mercado Avatar answered Jan 03 '23 01:01

Jeff Mercado