本体を .net クラス (辞書とリスト) に逆シリアル化したい。
(したがって、私のコードは xml と json に対して透過的です)
public HttpResponseMessage Post([FromBody]IDictionary<string, object> body)
{
}
現在、コンバーターを使用して、ネストされた辞書の逆シリアル化を処理しています。
class IDictionaryConverter : CustomCreationConverter<IDictionary<string, object>>
{
public override IDictionary<string, object> Create(Type objectType)
{
return new Dictionary<string, object>();
}
public override bool CanConvert(Type objectType)
{
// in addition to handling IDictionary<string, object>
// we want to handle the deserialization of dict value
// which is of type object
return objectType == typeof(object) || base.CanConvert(objectType);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.StartObject || reader.TokenType == JsonToken.Null)
return base.ReadJson(reader, objectType, existingValue, serializer);
// if the next token is not an object
// then fall back on standard deserializer (strings, numbers etc.)
return serializer.Deserialize(reader);
}
}
ただし、ネストされた JList は List に変換されません。IListConverter を作成できるかもしれませんが、これを行うためのより良い方法はありますか?
Web API に 1 つのコードのみが必要です。そうではありません: json がそれを行う場合、xml がそれを行う場合...