【问题标题】:Deserializing ambiguous json反序列化不明确的 json
【发布时间】:2011-06-28 13:07:13
【问题描述】:
public abstract class A {
    public string Foo{ get; set; }
}

public class B : A {
    public string Marco{ get; set; }
}

public class C : A {
    public string Las{ get; set; }
}

public class D : A {
    public string Las{ get; set; }
}

public class SerializeMe {
    [XmlElement("b", typeof(B))]
    [XmlElement("c", typeof(C))]
    [XmlElement("d", typeof(D))]
    public A[] serializeProp { get; set; }
}

SerializeMe me = new SerializeMe();
me.serializeProp = new A[]{
                           new B(){ Foo = "bar", Marco = "polo" },
                           new C(){ Foo = "bar", Las = "Vegas" },
                           new D(){ Foo = "bar", Las = "Vegas" }
                          };

XmlElement 属性控制 xml 序列化,因此这会导致:

 <SerializeMe>
    <B><Foo>bar</Foo><Marco>polo</Marco></B>
    <C><Foo>bar</Foo><Las>Vegas</Las></C>
    <D><Foo>bar</Foo><Las>Vegas</Las></D>
 </SerializeMe>

如果我要添加类似的属性以反序列化为 json(使用 Newtonsoft Json.Net 库):

{[
    {"Foo":"bar", "Marco":"polo"},
    {"Foo":"bar", "Las":"Vegas"},
    {"Foo":"bar", "Las":"Vegas"}
]}

但是,与 xml 不同的是,它不包含有关类型的详细信息,因此对我而言,它是否能正确识别要反序列化的类并不明显。无论如何使用现有的 json 结构正确反序列化,还是我必须修改 json 结构(以及如何最好地做到这一点)。

我想过重写序列化,使其产生以下格式:

{[
    {"class":"B",
     "object":{"Foo":"bar", "Marco":"polo"}},
    {"class":"C",
     "object":{"Foo":"bar", "Las":"Vegas"}},
    {"class":"D",
     "object":{"Foo":"bar", "Las":"Vegas"}}
]}

有没有更好的办法?

【问题讨论】:

    标签: c# xml json serialization


    【解决方案1】:

    您可以省略嵌套的"object"=,而只使用一个不是有效属性名称的字符串作为类标识符:

    {"Foo":"bar", "Marco":"polo", "$Class"="B"}
    

    JSON.net 内置了 TypeNameHandling 功能,生成的 json 如下所示:

    {"$type":"Tests.MessageWrapper2, Tests, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null",
    "Headers":{"$type":"System.Collections.Hashtable, mscorlib, Version=2.0.0.0, Culture=neutral,PublicKeyToken=b77a5c561934e089","DeliverAt":"yesterday!"},
    "Body":{"$type":"Tests.TestMessage1, Tests, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null","Id":893239}
    }
    

    请注意,如果您使用 TypeNameHandling,则 json 可以构造任意类型。因此,您可能不想反序列化来自不受信任来源的 json。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-08-28
      • 1970-01-01
      • 2019-05-02
      • 1970-01-01
      • 2015-01-04
      • 1970-01-01
      • 2019-08-21
      相关资源
      最近更新 更多