I'm currently making a simple config/option system using C# (mainly to replace the PlayerPrefs system in Unity). I orginally designed it similarly to an INI file but decided to take it a step further and use Json to allow infinite nesting of options.
The way the objects are essentially set up are: Option<T> {T Value} and Dictionary<string, Option>
With the previous INI design, it was:
[GRAPHICS]
Resolution=(X=1920, Y=1080)
With Json.NET, it's now:
"Graphics": {
"Value": {
"Resolution": {
"Value": {
"X": {
"Value": 1920
},
"Y": {
"Value": 1080
}
}
}
}
}
As you can see, it looks really messy and was wondering if there is any way I could make it shorter. For example: remove the "Value" part so it's like:
"Graphics": {
"Resolution": {
"X": 1920,
"Y": 1080,
}
}
The main goal is to make something that is fairly expandable whiles also being pretty easy to manually edit. Would simply just going to Yaml get me closer to this goal?
public class IOption // (changed to class from interface because Json.Net didn't like deserialising interface)
{
public virtual dynamic Value { get; set; }
public virtual bool SetValue(object value)
{
return false;
}
}
public class Option<T> : IOption
{
public override dynamic Value { get; set; }
public Option(T value)
{
Value = value;
}
public override bool SetValue(object value)
{
try
{
Value = (T)value;
return true;
}
catch (Exception e)
{
throw e;
}
}
}
void SaveToJson()
{
IDictionary parsableOptions = new Dictionary<string, IOption>();
Save("SomePath", parsableOptions);
}
public static void Save(string path, object obj)
{
var serializer = new Newtonsoft.Json.JsonSerializer();
using (var sw = new StreamWriter(path))
using (Newtonsoft.Json.JsonWriter writer = new Newtonsoft.Json.JsonTextWriter(sw))
{
writer.Formatting = Newtonsoft.Json.Formatting.Indented;
serializer.Serialize(writer, obj);
}
}
Update: Using dynamics in place of the IOptions class produced the result I wanted. I also moved to Yaml for it's easier to read aesthetic.