JsonConvert.DeserializeObject
成功将['a','b']
反序列化为List<KeyValuePair<string, object>>
。我希望它失败,只有在输入字符串如[{'Key':'a','Value':'b'}]
时成功。
有没有办法做到这一点?
最佳答案
看来您可能在Json.NET的KeyValuePairConverter
中发现了一个错误,即它假定读取器位于JSON对象的开头,而不是检查并验证它是否存在。如果需要,可以report an issue on it。
同时,以下JsonConverter
将针对您的情况正确抛出JsonException
:
public class KeyValueConverter : JsonConverter
{
interface IToKeyValuePair
{
object ToKeyValuePair();
}
struct Pair<TKey, TValue> : IToKeyValuePair
{
public TKey Key { get; set; }
public TValue Value { get; set; }
public object ToKeyValuePair()
{
return new KeyValuePair<TKey, TValue>(Key, Value);
}
}
public override bool CanConvert(Type objectType)
{
bool isNullable = (Nullable.GetUnderlyingType(objectType) != null);
Type type = (Nullable.GetUnderlyingType(objectType) ?? objectType);
return type.IsGenericType
&& type.GetGenericTypeDefinition() == typeof(KeyValuePair<,>);
}
public override bool CanWrite { get { return false; } } // Use Json.NET's writer.
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
bool isNullable = (Nullable.GetUnderlyingType(objectType) != null);
Type type = (Nullable.GetUnderlyingType(objectType) ?? objectType);
if (isNullable && reader.TokenType == JsonToken.Null)
return null;
if (type.IsGenericType
&& type.GetGenericTypeDefinition() == typeof(KeyValuePair<,>))
{
var pairType = typeof(Pair<,>).MakeGenericType(type.GetGenericArguments());
var pair = serializer.Deserialize(reader, pairType);
if (pair == null)
return null;
return ((IToKeyValuePair)pair).ToKeyValuePair();
}
else
{
throw new JsonSerializationException("Invalid type: " + objectType);
}
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
然后像这样使用它:
string json = @"['a','b']";
var settings = new JsonSerializerSettings { Converters = new JsonConverter[] { new KeyValueConverter() } };
var list = JsonConvert.DeserializeObject<List<KeyValuePair<string, object>>>(json, settings);
示例fiddle。
更新资料
要在JSON包含不存在的属性时强制错误,请使用
JsonSerializerSettings.MissingMemberHandling = MissingMemberHandling.Error
。 var settings = new JsonSerializerSettings
{
MissingMemberHandling = MissingMemberHandling.Error,
Converters = new JsonConverter[] { new KeyValueConverter() },
};