2014-03-13 31 views
0

抛出异常:Newtonsoft的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); 

回答

2

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

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

+0

谢谢你,那是问题:) – user3415793