Skip to content

Commit

Permalink
Add support for dictionaries to JsonSerializationWriter.
Browse files Browse the repository at this point in the history
  • Loading branch information
greg-ww committed Jul 25, 2024
1 parent 0ff5ada commit 7d791dd
Showing 1 changed file with 31 additions and 0 deletions.
31 changes: 31 additions & 0 deletions src/serialization/json/JsonSerializationWriter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
using Microsoft.Kiota.Abstractions;
using Microsoft.Kiota.Abstractions.Extensions;
using Microsoft.Kiota.Abstractions.Serialization;
using System.Collections;

#if NET5_0_OR_GREATER
using System.Diagnostics.CodeAnalysis;
Expand Down Expand Up @@ -360,6 +361,33 @@ public void WriteCollectionOfEnumValues<T>(string? key, IEnumerable<T?>? values)
}
}
/// <summary>
/// Writes the specified dictionary to the stream with an optional given key.
/// </summary>
/// <param name="key">The key to be used for the written value. May be null.</param>
/// <param name="values">The dictionary of values to be written.</param>
#if NET5_0_OR_GREATER
public void WriteDictionaryValue<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields)] T>(string? key, T values) where T : IDictionary
#else
public void WriteDictionaryValue<T>(string? key, T values) where T : IDictionary
#endif
{
if(values != null)
{
if(!string.IsNullOrEmpty(key))
writer.WritePropertyName(key!);
var type = values.GetType();
if(!type.IsGenericType || type.GetGenericArguments()[0] != typeof(string))
throw new InvalidOperationException($"error serialization additional data value with key {key}, unsupported type {type}");

writer.WriteStartObject();
foreach(DictionaryEntry entry in values)
{
WriteAnyValue((string)entry.Key, entry.Value);
}
writer.WriteEndObject();
}
}
/// <summary>
/// Writes the specified byte array as a base64 string to the stream with an optional given key.
/// </summary>
/// <param name="key">The key to be used for the written value. May be null.</param>
Expand Down Expand Up @@ -512,6 +540,9 @@ private void WriteAnyValue<T>(string? key, T value)
writer.WritePropertyName(key!);
jsonElement.WriteTo(writer);
break;
case IDictionary dictionary:
WriteDictionaryValue(key, dictionary);
break;
case object o:
WriteNonParsableObjectValue(key, o);
break;
Expand Down

0 comments on commit 7d791dd

Please sign in to comment.