Created
May 30, 2023 15:48
-
-
Save AndyButland/03108ff4f7a968bf6993084d85b5a268 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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