I want to use JSON.Net to serialize a complex C#.net object into JSON. The class structure is flexible (completely under my control), but JSON is needed in a specific format to communicate with another application. I require JSON in the following format, but need assistance composing the classes and nested collections:
{
"Record_1": [ { "key_1": "value_1", "key_N": "value_N"}, { "key_1": "value_1", "key_N": "value_N"}],
"Record_2": [ { "key_1": "value_1" } ],
"Record_N": [ { "key_1": "value_1" } , { "key_N":"value_N"}],
… Other properties (simple string key value pairs)
}
- There will be 1 or more Record properties, the value of each Record is an array of objects.
- The Record property names are not known (I have a list of possibilities, but do not want to hardcode them into the application).
- There will be 1 or more objects in each array.
- The objects in the array will have 1 or more string key value pairs. Again, property names are not known at compile time.
Since the Record properties were unknown, I tried using a dictionary of objects (Dictionary<string,object>) annotated with [JsonExtensionData]. The value object in the dictionary was another collection. However, that results in string properties with object values:
"Record_1": { key_1: [ value_1, value_2, value_N] }, "Record_N": { key_1: [value_1] }
Close, but not correct, the value of Record has to be an array.
Next, I tried using a list of lists of objects, but that didn't work either because the variable names of the lists are returned as the property names:
"RecordSet": [
{
"Records": [
{
"Key_1": "Value_1"
}
]
},
{
"Records": [
{
"Key_1": "Value_1",
}
]
}
]
So this does result in an array objects, but contents of the object are not in the correct form.
I believe I need some combination of nested collections in my class to output the records in the required JSON format, but I don't know which. Hopefully someone else has encountered this situation before.
BTW: Currently, I'm directly writing to the JSON object to get the structure required. I'm hoping that there will be some performance increase in refactoring for serialization. I'm not looking to just add complexity so I can say I'm following object oriented coding principles. There will never be a need for deserialization of this JSON back into an object.
Dictionary<string, string>or adynamicto hold the things that look like{ "key_1": "value_1", "key_N": "value_N"}. If you don't know what the property names are, you can't just use a plain old class