反序列化对象时出现意外的标记:EndObject。路径'[0]'

时间:2015-01-10 04:33:15

标签: c# json json.net

我正在尝试使用NewtonSoft.Json将JSON derserialize为字符串字符串。这是JSON:

"order_meta":{"override_global_product_limit":"no","purchase_limit":{"min":0,"max":0}}}]}

这些是自定义字段,因此名称和子字段(如purchase_limit)随每个网站而变化。将这些值反序列化为类是不可能的。这是我的班级:

    [JsonConverter(typeof(DictionaryConverter))]
    public Dictionary<string, string> order_meta { get; set; }


public class DictionaryConverter : JsonConverter
{
    public override bool CanWrite { get { return false; } }
    public override bool CanConvert(Type objectType)
    {
        return objectType == typeof(Dictionary<string, string>);
    }
    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        if (reader.TokenType == JsonToken.StartArray)
        {
            reader.Read();
            if (reader.TokenType == JsonToken.EndArray)
                return new Dictionary<string, string>();
            else
                throw new JsonSerializationException("Non-empty JSON array does not make a valid Dictionary!");
        }
        else if (reader.TokenType == JsonToken.Null)
        {
            return null;
        }
        else if (reader.TokenType == JsonToken.StartObject)
        {
            Dictionary<string, string> ret = new Dictionary<string, string>();
            reader.Read();
            while (reader.TokenType != JsonToken.EndObject)
            {
                if (reader.TokenType == JsonToken.EndArray)
                {
                    reader.Read();
                    continue;
                }

                if (reader.TokenType != JsonToken.PropertyName)
                    throw new JsonSerializationException("Unexpected token!");

                string key = (string)reader.Value;
                reader.Read();

                if (reader.TokenType == JsonToken.StartArray)
                {
                    reader.Read();
                }

                if (reader.TokenType == JsonToken.StartObject)
                {
                    reader.Read();

                    if (reader.TokenType == JsonToken.PropertyName)
                    {
                        key = (string)reader.Value;
                        reader.Read();
                    }
                }

                //if (reader.TokenType != JsonToken.String && reader.TokenType != JsonToken.Integer)
                //    throw new JsonSerializationException("Unexpected token!");

                string value = Convert.ToString(reader.Value);
                ret.Add(key, value);
                reader.Read();
            }
            return ret;
        }
        else
        {
            throw new JsonSerializationException("Unexpected token!");
        }
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }
}

}

0 个答案:

没有答案