Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 防止Json.NET将字符串数组反序列化为键值对数组_C#_Json_Json.net - Fatal编程技术网

C# 防止Json.NET将字符串数组反序列化为键值对数组

C# 防止Json.NET将字符串数组反序列化为键值对数组,c#,json,json.net,C#,Json,Json.net,JsonConvert.DeserializeObject成功地将['a','b']反序列化为列表。我希望它失败,只有当输入字符串像[{'Key':'a','Value':'b}]时才会成功 有没有办法做到这一点?看来您可能在Json.NET中发现了一个bug,即它假设读者位于Json对象的开头,而不是检查和验证它是否在。如果你愿意,你可以 同时,以下内容将正确地为您的案例提供支持: public class KeyValueConverter : JsonConverter { int

JsonConvert.DeserializeObject
成功地将
['a','b']
反序列化为
列表
。我希望它失败,只有当输入字符串像
[{'Key':'a','Value':'b}]
时才会成功


有没有办法做到这一点?

看来您可能在Json.NET中发现了一个bug,即它假设读者位于Json对象的开头,而不是检查和验证它是否在。如果你愿意,你可以

同时,以下内容将正确地为您的案例提供支持:

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();
    }
}

嗯,您必须读取字符串并使用正则表达式测试它是否具有所需的格式。@xsquared您可以发布一个验证任何json的正则表达式吗?我想知道这是内在的(“硬编码”)还是通过一个标准转换器。@user2864740发布一个真正的注释而不是取笑我的english@user2864740好啊那你是什么意思?谢谢,这使得它像“['a','b']”预期的那样失败了。然而,它仍然成功地实现了以下功能,它们似乎也应该失败:[{'a':'b','c':'d'}](因为它的字段没有命名为Key和Value)和“[{'Key':{'x':1},'Value':false}](因为键不是字符串)。你知道如何用通用的方式解决这个问题(不需要硬编码转换器)?
        string json = @"['a','b']";

        var settings = new JsonSerializerSettings { Converters = new JsonConverter[] { new KeyValueConverter() } };
        var list = JsonConvert.DeserializeObject<List<KeyValuePair<string, object>>>(json, settings);
        var settings = new JsonSerializerSettings
        {
            MissingMemberHandling = MissingMemberHandling.Error,
            Converters = new JsonConverter[] { new KeyValueConverter() },
        };