我已经用 JSON 序列化了嵌套对象,我该如何反序列化它们?

I have serialized nested objects with JSON, how do I deserialize them?

我在反序列化时不断收到“阅读完 JSON 内容后遇到的其他文本”。我试过将整个“输出”放入方括号中,但没有成功。

完整的错误信息

Newtonsoft.Json.JsonReaderException: 
'Error reading JObject from JsonReader. Current JsonReader item is not an object: 
StartArray. Path '', line 1, position 1.'

这是我的 2 个对象。注意:当前对值进行注释以便于“输出”阅读。

class ItemSerObj
{
    public string ItemName { get; set; }
    /*
    public string Value { get; set; }
    public string Quality { get; set; }
    public string TimeStamp { get; set; }*/
}

.

class GroupSerObj
{
    public string GroupName { get; set; }
    /*
    public string UpdateRate { get; set; }
    public string Active { get; set; }*/
    public List<ItemSerObj> Items { get; set; }
}

我是如何序列化它们的。

JsonSerializer serializer = new JsonSerializer();
        using (StreamWriter sw = new StreamWriter(path + "\data.txt"))
        {
            using (JsonWriter writer = new JsonTextWriter(sw))
            {
                foreach (ListViewItem group in lV_groups.Items)
                {
                    List<ItemSerObj> itemsObj = new List<ItemSerObj>();
                    tempOPCServer.opcGroup = tempOPCServer.opcServer.OPCGroups.GetOPCGroup(group.SubItems[0].Text);
                    foreach (OPCItem item in tempOPCServer.opcGroup.OPCItems)
                    {
                        ListViewItem listViewItem = new ListViewItem();
                        listViewItem.Name = item.ItemID.Substring(item.ItemID.LastIndexOf('.') + 1);
                        itemsObj.Add(
                        new ItemSerObj
                        {
                            ItemName = listViewItem.Name
                            /*ItemName = item.SubItems[0].Text/*,
                            Value = item.SubItems[1].Text,
                            Quality = item.SubItems[2].Text,
                            TimeStamp = item.SubItems[3].Text*/
                        });
                    }

                    GroupSerObj serializeGroup = new GroupSerObj
                    {
                        GroupName = group.SubItems[0].Text,/*
                        UpdateRate = group.SubItems[1].Text,
                        Active = group.SubItems[2].Text,*/
                        Items = itemsObj
                    };

                    serializer.Serialize(writer, serializeGroup);
                }
            }
        }

输出。

{"GroupName":"Group0","Items":[{"ItemName":"Int1"},{"ItemName":"Money"},{"ItemName":"Int4"},{"ItemName":"Int2"}]}{"GroupName":"Group1","Items":[]}{"GroupName":"Group2","Items":[]}

更具可读性的排序

{"GroupName":"Group0","Items":[
    {"ItemName":"Int1"},
    {"ItemName":"Money"},
    {"ItemName":"Int4"},
    {"ItemName":"Int2"}]}
{"GroupName":"Group1","Items":[
    ]}
{"GroupName":"Group2","Items":[
]}

我试图反序列化它。

string fromJson;
        using (StreamReader sr = new StreamReader(path + "\data.txt"))
        {
            fromJson = @sr.ReadLine();
        }
        JObject fromJsonObject = JObject.Parse(fromJson); //Where exeption occurs.


        IList<JToken> results = fromJsonObject["Items"]["ItemName"].Children().ToList();

        IList<GroupSerObj> deserResults = new List<GroupSerObj>();

        foreach(JToken result in results)
        {
            GroupSerObj deserResult = result.ToObject<GroupSerObj>();
            deserResults.Add(deserResult);
        }

对我来说,你的输出看起来是错误的。它是一个对象数组(多个组),所以它应该被 [] 包围,每个对象用逗号分隔(,)。

您的输出应如下所示:

[{"GroupName":"Group0","Items":[{"ItemName":"Int1"},{"ItemName":"Money"},{"ItemName":"Int4"},{"ItemName":"Int2"}]},{"GroupName":"Group1","Items":[]},{"GroupName":"Group2","Items":[]}]

您正在使用 JObject 来解析数组,但是在解析数组时我们需要 JArray,所以它应该是:

JArray fromJsonObject = JArray.Parse(fromJson); //Where exeption occurs.
for (int i = 0; i < fromJsonObject.Count; i++)
   {
       IList<GroupSerObj> deserResults = new List<GroupSerObj>();
       var deserResult = fromJsonObject[i].ToObject<GroupSerObj>();
       deserResults.Add(deserResult);
   }