How do I easily modify *any* property/object/nested object of C# deserialized .json?
config/data.json
{
"title": "XYZ",
"obj1": {
"s1": -1,
"s2": "auto",
"s3": false,
},
"obj2": {
"s1": true,
"s4": [
[5,0],
[4,1]
]
},
"obj3": [
{
"s3": "s",
}
],
}
program.cs
// Classes for JSON de-serialization
`public class Obj1
{
public int s1 { get; set; }
public string s2 { get; set; }
public bool s3 { get; set;}
}
public class Obj2
{
public bool s1 { get; set; }
public IList<IList<int>> s4 { get; set; }
}
public class Obj3
{
public string s3 { get; set; }
}
public class Example
{
public string title { get; set; }
public Obj1 obj1 { get; set; }
public Obj2 o2 { get; set; }
public IList<Obj3> obj3 { get; set; }
}
//Methods to modify JSON
private static string rigJsonPath =
Path.Combine(AppDomain.CurrentDomain.BaseDirectory, Path.Combine("config", "data.json"));
public static Example ReadAndDeserialize()
{
string json = File.ReadAllText(rigJsonPath);
Example ex = JsonSerializer.Deserialize<Example>(json)!;
return ex;
}
public static void SerializeAndWrite(Example ex)
{
string json = JsonSerializer.Serialize(ex);
File.WriteAllText(rigJsonPath, json);
}
public static void ModifyProperty(Example ex, string propertyName, object propertyValue)
{
switch (propertyName)
{
case "obj1.s1":
ex.obj1!.s1 = (int)propertyValue;
break;
// etc
}
}
I want to be able to modify any property/object of JSON through a method in C#.
I'd like to create a universal method for this task. The switch is a monkey solution, can't write for lots of objects.
{
"title": "XYZ",
"obj1": {
"s1": -1,
"s2": "auto",
"s3": false,
},
"obj2": {
"s1": true,
"s4": [
[5,0],
[4,1]
]
},
"obj3": [
{
"s3": "s",
}
],
}
program.cs
// Classes for JSON de-serialization
`public class Obj1
{
public int s1 { get; set; }
public string s2 { get; set; }
public bool s3 { get; set;}
}
public class Obj2
{
public bool s1 { get; set; }
public IList<IList<int>> s4 { get; set; }
}
public class Obj3
{
public string s3 { get; set; }
}
public class Example
{
public string title { get; set; }
public Obj1 obj1 { get; set; }
public Obj2 o2 { get; set; }
public IList<Obj3> obj3 { get; set; }
}
//Methods to modify JSON
private static string rigJsonPath =
Path.Combine(AppDomain.CurrentDomain.BaseDirectory, Path.Combine("config", "data.json"));
public static Example ReadAndDeserialize()
{
string json = File.ReadAllText(rigJsonPath);
Example ex = JsonSerializer.Deserialize<Example>(json)!;
return ex;
}
public static void SerializeAndWrite(Example ex)
{
string json = JsonSerializer.Serialize(ex);
File.WriteAllText(rigJsonPath, json);
}
public static void ModifyProperty(Example ex, string propertyName, object propertyValue)
{
switch (propertyName)
{
case "obj1.s1":
ex.obj1!.s1 = (int)propertyValue;
break;
// etc
}
}
I want to be able to modify any property/object of JSON through a method in C#.
I'd like to create a universal method for this task. The switch is a monkey solution, can't write for lots of objects.