引发了Newtonsoft Json .NET异常

时间:2014-03-13 14:23:01

标签: c# json serialization json.net

抛出异常:

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

1 个答案:

答案 0 :(得分:2)

您需要为要反序列化的类型创建默认构造函数。

否则,JSON.Net将尝试反序列化到与您的JSON不匹配的构造函数参数。