【问题标题】:Mismatched group tags detected in message - protobuf-net在消息中检测到不匹配的组标签 - protobuf-net
【发布时间】:2010-02-10 11:00:17
【问题描述】:

我对 Silverlight 很陌生。我正在为一个主要依赖于序列化和反序列化的项目工作。

以前,对于 WPF,我对 Serializable 类感到满意。对于 silverlight,我发现 protobuf 会非常有用。但是,我对这个例外感到困扰。我不知道是什么导致了这个问题。请帮帮我。

我正在使用 Silverlight 3.0。 protobuf-net r282

请找到我正在使用的代码。

[ProtoContract]
public class Report
{
    public Report()
    {
    }

    [ProtoMember(1)]
    public SubReports SubReports { get; set; }
}

[ProtoContract]
public class SubReports
   : List<SubReport>
{
    public SubReports()
    {
    }

    [ProtoMember(1)]
    public SubReport SubReport { get; set; }
}

[ProtoContract]
public class SubReport
{
    public SubReport()
    {
    }

    [ProtoMember(1)]
    public string Name { get; set; }
}

我用来反序列化的代码是

    public static T Deserialize<T>(Byte[] bytes) where T
        : Report
    {
        return ProtoBuf.Serializer.Deserialize<T>(new MemoryStream(bytes));
    }

我的示例 XML 看起来类似于

Report  
   ...SubReports  
      ...SubReport Name=”Q1 Report”   
      ...SubReport Name=”Q2 Report”   
      ...SubReport Name=”Q3 Report”   
      ...SubReport Name=”Q4 Report”     

提前致谢。
维诺德

【问题讨论】:

    标签: serialization protobuf-net


    【解决方案1】:

    (注意:我无法重现“组标签”问题;请参阅编辑历史以了解我对此的最初想法,现已删除;如果您能帮助我重现此问题,我将不胜感激)

    问题是SubReports。您已将此 both 定义为列表 定义为序列化实体 ([ProtoContract]);后者优先,因此它试图序列化列表中的 single 子报告(始终为null?)。

    如果您将其更改为:

    // note no attributes, no child property
    public class SubReports : List<SubReport> { }
    

    或者,如果您将其完全删除并将Report.SubReports 设置为List&lt;SubReport&gt;,它应该可以正常工作。以下作品:

    static void Main() {
        byte[] blob;
        // store a report
        using (MemoryStream ms = new MemoryStream()) {
            Report report = new Report {
                SubReports = new List<SubReport> {
                    new SubReport { Name="Q1"}, 
                    new SubReport { Name="Q2"},
                    new SubReport { Name="Q3"},
                    new SubReport { Name="Q4"},
                }
            };
    
            Serializer.Serialize(ms, report);
            blob = ms.ToArray();
        }
        // show the hex
        foreach (byte b in blob) { Console.Write(b.ToString("X2")); }
        Console.WriteLine();
    
        // reload it
        using (MemoryStream ms = new MemoryStream(blob)) {
            Report report = Serializer.Deserialize<Report>(ms);
            foreach (SubReport sub in report.SubReports) {
                Console.WriteLine(sub.Name);
            }
        }
    }
    

    显示 blob:

    0A040A0251310A040A0251320A040A0251330A040A025134

    【讨论】:

    • 非常感谢 marc 的快速响应。我会调查一下。
    • 嗨,Marc,您的最后一个回答本身就解决了我的问题。实际上,我正在尝试反序列化一个 xml 文件并填充类,就像我们在桌面应用程序中使用的 [Serializable] 一样。是的,通过使用上述建议,我在“子报表”中得到了“空”。感谢您的更新:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-21
    • 1970-01-01
    • 2017-04-03
    • 1970-01-01
    • 2018-08-28
    相关资源
    最近更新 更多