Skip to content

Instantly share code, notes, and snippets.

@AndyButland
Created May 30, 2023 15:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AndyButland/03108ff4f7a968bf6993084d85b5a268 to your computer and use it in GitHub Desktop.
Save AndyButland/03108ff4f7a968bf6993084d85b5a268 to your computer and use it in GitHub Desktop.
internal class MyApiPostedValuesConverter : JsonConverter
{
public override bool CanConvert(Type objectType) => objectType == typeof(IDictionary<string, IList<string>>);
public override object ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer)
{
var properties = JToken.Load(reader).Cast<JProperty>().ToList();
var result = new Dictionary<string, IList<string>>();
foreach (JProperty property in properties)
{
List<string> values;
if (property.Value.Type == JTokenType.Array)
{
values = ((JArray)property.Value)
.Select(ValueOrObjectToString)
.ToList();
}
else
{
values = new List<string> { property.Value.ToString() };
}
result.Add(property.Name, values);
}
return result;
}
private static string ValueOrObjectToString(JToken jtoken) =>
jtoken is JValue jvalue
? jvalue.ToString()
: ((JObject)jtoken).ToString(Formatting.None);
public override bool CanWrite => false;
public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer) => throw new NotImplementedException();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment