Easier way to flatten an object with STJ serialization #77206
-
Recently I meet a requirement that serializes a object with STJ. See the example below, public ItemsData Item = new()
{
// Skip others' initialization
Dynamics = new()
{
{ "prop1", "1" },
{ "prop2", "2" },
{ "prop3", "3" },
}
};
public class ItemsData
{
public int Id { get; set; }
public string Name { get; set; }
// Skip many other properties
public Dictionary<string, string> Dynamics{ get; set; }
} The expected Json is It's easy to be done with a specific public override void Write(Utf8JsonWriter writer, ItemsData value, JsonSerializerOptions options)
{
var namingPolicy = options?.PropertyNamingPolicy;
writer.WriteStartObject();
writer.WriteNumber(GetPropName(nameof(value.Id), namingPolicy), value.Id);
writer.WriteString(GetPropName(nameof(value.Name), namingPolicy), value. Name);
// Skip a lot of lines
if (value.Dynamics?.Count > 0)
{
foreach (var item in value. Dynamics)
{
writer.WriteString(item.Key, item. Value);
}
}
writer.WriteEndObject();
}
private static string GetPropName(string name, JsonNamingPolicy policy)
{
return policy == null
? name
: policy.ConvertName(name);
} Any better solutions? Thanks in advance. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
Does |
Beta Was this translation helpful? Give feedback.
Does
[JsonExtensionData]
on the dictionary property not work for you? A potential downside is that you'd have to change the dictionary's value type to eitherobject
orJsonElement
.