Newtonsoft Json .NET exception thrown



异常投掷:

Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[Messages.ObjectDescription]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.

如果有人能弄清楚,我将感谢您的帮助。基本上,我实例化了一个名为Messagess的类,将其序列化至JSON字符串,然后尝试进行序列化并将异常抛弃。

这是我的课程:

[JsonConverter(typeof(StringEnumConverter))]
    public enum MessageType
    {
        req_authenticate,
        c_data,
        req_state,
        c_cmd,
        resp_authenticate,
        s_cmd,
        s_data,
        resp_state,
        s_state
    }
public interface IData { }
    public abstract class Message
    {
        public MessageType type { get; set; }
        public virtual string GetJson()
        {
            return JsonConvert.SerializeObject(this, Formatting.Indented, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
        }
    }
public class ObjectDescription
    {
        public string key { get; set; }
        public string type { get; set; }
        public double value { get; set; }
        public Quality quality { get; set; }
        public DateTime timestamp { get; set; }
        public ObjectDescription(string _key, string _type, double _value, Quality _quality, DateTime _timestamp)
        {
            key = _key;
            type = _type;
            value = _value;
            quality = _quality;
            timestamp = _timestamp;
        }
    }
public class MessageSSData : IData
    {
        public State state { get; set; }
        public List<ObjectDescription> data { get; set; }
        public MessageSSData(State _state, List<ObjectDescription> _data)
        {
            state = _state;
            this.data = _data;
        }
    }
    public class MessageSS : Message
    {
        public MessageSSData data { get; set; }
        public MessageSS(State state, List<ObjectDescription> data)
        {
            type = MessageType.s_state;
            this.data = new MessageSSData(state, data);
        }
    }
//Here is the code that throws the exception:
MessageSS mm = new MessageSS(State.CONNECTING, new ObjectDescription[2] { new ObjectDescription("prvi", "tip1", 1.1, Quality.BAD, new DateTime()), 
                new ObjectDescription("drugi", "tip2", 1.2, Quality.GOOD, new DateTime()) }.ToList());
            string json2 = mm.GetJson();
            MessageSS mm2 = JsonConvert.DeserializeObject<MessageSS>(json2);

您需要为您供应到的类型创建一个默认的构造函数。

否则,JSON.NET将尝试将其划分为您的构造函数参数,而构造函数参数与您的JSON不匹配。

相关内容

  • 没有找到相关文章

最新更新