CodeFluent JSON Serialization Does Not Work for All Fields
See the question and my original answer on StackOverflowThe problem comes from the fact you're creating a model error with an empty key. It's not forbidden but JsonUtilities just skip dictionary values with an empty key, by design.
Just use a real key, like this:
ModelState.AddModelError("my first error", "An Error!");
ModelState.AddModelError("my second error", "An Error!");
And you'll see the errors collection serialized, like this:
{
"Data":[
{
"ExampleProperty":"ExampleValue"
}],
"Total": 1,
"AggregateResults": null,
"Errors": {
"my first error": {
"errors": [
"An Error!"
]
},
"my second error": {
"errors": [
"An Error!"
]
}
}
}
Otherwise, if you really want to keep empty keys, then you can leverage the JsonUtilitiesOptions
class that has callbacks for tweaking the serialization (and deserialization) process. Careful with this as you can easily break JSON syntax. This is how you could do it, in a way that should handle all cases:
JsonUtilitiesOptions options = new JsonUtilitiesOptions();
options.WriteValueCallback += (e) =>
{
IDictionary valueDic = e.Value as IDictionary;
if (valueDic != null)
{
e.Writer.Write('{');
bool first = true;
foreach (DictionaryEntry entry in valueDic)
{
if (!first)
{
e.Writer.Write(',');
}
else
{
first = false;
}
// reuse JsonUtilities already written functions
JsonUtilities.WriteString(e.Writer, entry.Key.ToString(), e.Options);
e.Writer.Write(':');
// object graph is for cyclic/infinite serialization checks
JsonUtilities.WriteValue(e.Writer, entry.Value, e.ObjectGraph, e.Options);
}
e.Writer.Write('}');
e.Handled = true; // ok, we did it
}
};
string json = JsonUtilities.Serialize(obj, options);
Now, you'll get this result:
{
"Data":[
{
"ExampleProperty":"ExampleValue"
}],
"Total": 1,
"AggregateResults": null,
"Errors": {
"": {
"errors": [
"An Error!"
]
}
}
}