I am trying to build a JsonElement (or similar) using a camelCase convention from a PascalCase string using System.Text.Json. Is there a way to enforce that behavior?
var jsonString = "{"Property1":"s", "PropertyCamel":{"PropertyNested":"g"}, "PPP":[{"NestedList":"1"}]}";
var deserialized = System.Text.Json.JsonSerializer.Deserialize<JsonElement>(jsonString,
new JsonSerializerOptions
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
DictionaryKeyPolicy = JsonNamingPolicy.CamelCase,
PropertyNameCaseInsensitive = true
});
var serialized = System.Text.Json.JsonSerializer.Serialize(
deserialized,
new JsonSerializerOptions
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
DictionaryKeyPolicy = JsonNamingPolicy.CamelCase,
PropertyNameCaseInsensitive = true
});
// deserialized outputs property names in PascalCase
I have also tried deserializing -> serializing -> deserializing but without success.
Is there a way of doing so?
2
Answers
Referring to this answer, using Newtonsoft.Json
There is no way to load or deserialize a
JsonDocument
orJsonElement
and convert it to camelCase during the loading process.JsonDocument
andJsonElement
are just read-only, structured views of the utf-8 JSON byte sequence from which they were loaded and as such there’s no way to transform the view during (or after) the parsing process. For confirmation,JsonDocument
,JsonElement
andUtf8JsonReader
are allsealed
andJsonElement
has no publicly accessible constructor so there simply isn’t an extension point to inject custom transformation of property names.As an alternative, you could camel-case the property names during re-serialization by creating the following custom
JsonConverter<JsonElement>
:And then re-serializing your
JsonDocument.RootElement
usingJsonSerializer
like so:Notes:
Be sure to serialize the
JsonDocument.RootElement
rather than theJsonDocument
. If you serialize the document directly the converter is never invoked.In .NET 6 it should be possible to transform the property names during deserialization/loading using a custom converter by deserializing to the new
JsonNode
DOM, whose elements can be constructed and modified directly by applications code.As an alternative, if you don’t require use of
JsonElement
, you could consider deserializing to anExpandoObject
or similar and remapping the properties during deserialization by extendingObjectAsPrimitiveConverter
from this answer to C# – Deserializing nested json to nested Dictionary<string, object> to do the necessary name transformation.Demo fiddle here.