2017-12-18 257 views
0

我做了一个自定义JSON转换器来处理我收到的JSON,但我有一些解析嵌套对象列表的麻烦。我的JSON目前看起来像这样:反序列化自定义JsonConverter中的嵌套对象列表

JSON: 

{ 
"messageID": "1", 
"item": 
    { "type": "text", 
    "textlist": [ { "text": "just some text" }] 
    } 
} 

在我的情况下,我创建了几个类可以转换为。我有一个消息类应用转换器的项目。 item属性是一个接口,它具有TextItem类形式的实现。

public class Message 
    { 
    [JsonProperty("messageID")] 
    public string messageID { get; set; } 

    [JsonConverter(typeof(ItemConverter))] 
    public IItem item { get; set; } 

    public Message(string msgID, IItem itm) 
    { 
     messageID = msgID; 
     item = itm; 
    } 
} 

public class TextItem : IItem 
{ 
    [JsonProperty("type")] 
    public string type { get; set; } 
    [JsonProperty("textlist")] 
    public List<Text> textlist { get; set; } 

    string IItem.Type 
    { 
     get => type; 
     set => type = value; 
    } 

    public TextItem(List<Text> txtlst) 
    { 
     type = "text"; 
     textlist = txtlst; 
    } 
} 

public class Text 
{ 
    [JsonProperty("text")] 
    public string text { get; set; } 

    public Text(string txt) 
    { 
     text = txt; 
    } 
} 

有相当多的不同类型的项目,这就是为什么我有ItemConverter:

public class ItemConverter : JsonConverter 
    { 
     public override object ReadJson(JsonReader reader, 
     Type objectType, object existingValue, 
     JsonSerializer serializer) 
    { 
     var jsonObject = JObject.Load(reader); 
     var item= default(IItem); 
     switch (jsonObject["type"].Value<string>()) 
     { 
      case "text": 
       item= new TextItem(jsonObject["textlist"].Value<List<Text>>()); 
       break; 
    // omitted non relevant cases 
     } 

     serializer.Populate(jsonObject.CreateReader(), item); 
     return item; 
    } 
} 

然而,调用DeserializeObject只会导致错误

JsonConvert.DeserializeObject<Message>(userMessage) 

// I get the following error: 
System.ArgumentNullException: Value cannot be null. 

所有我的其他案例(没有列表)处理得很好。关于为什么嵌套列表未正确转换的任何想法?

回答

0

你的类都搞砸了,

使用public string type { get; set; }让你的项目,你需要

你的类可能是这个样子

public class Textlist 
{ 
    public string text { get; set; } 
} 

public class Item 
{ 
    public string type { get; set; } 
    public List<Textlist> textlist { get; set; } 
} 

public class RootObject 
{ 
    public string messageID { get; set; } 
    public Item item { get; set; } 
} 

,现在你可以在RootObject

反序列化
+0

我按照你所描述的修复了我的课程(也在原始文章中更新了它)。它仍然产生相同的结果。 – Tippi

+0

犯了小错,这是正确的答案 – Tippi

相关问题