public class MyClass
{
public string SomeProperty { get; set; }
public List<ChildClass> Items { get; set; }
}
public class ChildClass
{
public string IDProperty { get; set; }
public string SomeOtherProperty { get; set; }
}
I'm writing an object that is in essence the above-defined object to a JSON string using NewtonSoft (12), but depending on the method I'm calling from I want JObject.FromObject(MyClassInstance)
' to output the subitems as a JSON array, and sometimes as a JSON dictionary (using IDProperty
as the dictionary key).
I tried using a JsonConverter
and was able to use the WriteJson
method to output both ways (by casting the list to a dictionary or an array before serializing with serializer.Serialize(writer, value)
) but I wasn't able to figure out how to 'tell' the JsonConverter which way to pick as I call JObject.FromObject(MyClassInstance)
. My best guess is passing down a parameter within a Serializer I pass down in FromObject, but I wasn't able to find a place to pass down that info.
So, to be clear, without changing the Class attributes themselves, I'd like to be able to toggle between outputting:
{
"SomeProperty": "myID",
"Items": [
{
"cc1IDProperty": "1",
"SomeOtherProperty": "2"
},
{
"cc1IDProperty": "2",
"SomeOtherProperty": "4"
}
]
}
and
{
"SomeProperty": "myID",
"Items": {
"1": {
"cc1IDProperty": "1",
"SomeOtherProperty": "2"
},
"2": {
"cc1IDProperty": "2",
"SomeOtherProperty": "4"
}
}
}