C
C#•4mo ago
Mikson

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.
8 Replies
Angius
Angius•4mo ago
You can't
Mikson
Mikson•4mo ago
Really? 🥲
Angius
Angius•4mo ago
Welcome to a strongly and statically-typed language You can't just willy-nilly access whatever by whatever and set it to whatever Maybe with reflections Or with JsonDocument or something But there's no reason to Just... modify the object, without any random helper method Foo.Bar.Baz.Quz = 58
Mikson
Mikson•4mo ago
Okay but what if I want to be able to modify each element? I want an option to do so. Should I create a method for each property then? Each property will have its own function There's no way to solve this? Essentially I wanted to be able to modify any property from the command line, make it interactive and fast when working with bigger Json files
Angius
Angius•4mo ago
Some sort of a weird JSON editor?
Mikson
Mikson•4mo ago
Kind of Json should be edited manually? Isn't it sort of database? I'm sorry if I sound gullible, I'm very much a beginner
Angius
Angius•4mo ago
Well, JSON is a human-readable and human-editable format So I don't see much of a reason for some CLI editor to exist, if you can just open the file in Notepad
Mikson
Mikson•4mo ago
What kind of light database I could work with to interact with through the CLI then Damn, it is so right, json is human readable
Want results from more Discord servers?
Add your server
More Posts