Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding property to a json object in C#

Tags:

json

c#

json.net

I'm trying to add a property to a json object, which are not root of the json.

example is below.

{
    'isFile' : 'true',
    'Values' : {
        'valueName1': 'value1',
        'valueName2': 'value2',
        'valueName3': 'value3',
    }
}

after the operation, i want the json file to look like below.

{
    'isFile' : 'true',
    'Values' : {
        'valueName1': 'value1',
        'valueName2': 'value2',
        'valueName3': 'value3',
        'valueName4': 'value4'
    }
}

I have gotten to the point where I can access Values property through below code. Where do I go next?

JObject appSettings = JsonConvert.DeserializeObject<JObject>(jsonString);
string values = appSettings["Values"].ToString();

any help?

*Edit I'm trying to edit values section for local.settings.json file for azure app function in Visual Studio.

like image 731
Evan Park Avatar asked Apr 23 '18 20:04

Evan Park


1 Answers

you can do it with a dynamic object

        dynamic obj = JsonConvert.DeserializeObject<ExpandoObject>(jsonString);
        obj.Values.valueName4 = "value4";
        System.Console.WriteLine(JsonConvert.SerializeObject(obj));
like image 160
Isitar Avatar answered Oct 12 '22 05:10

Isitar