我需要完成一个非常简单的任务:序列化和反序列化对象层次结构。
我已经尝试过XMLSerializer
,DataContractSerializer
,NetDataContractSerializer
,但是似乎没有任何效果,总是有一些问题。
XMLSerializer
不好,因为它要求所有属性都是公共的。
(Net)DataContractSerializer不好,因为它总是缺少一些元数据-但是,当用户创建XML时,没有元数据。
那么,您将如何解决此任务?考虑类:
class A {
private B instanceB;
private int integerValue;
... getters/setters
}
class B {
private List<C> cInstanceList;
private string stringValue;
... getters/setters
}
class C {
... some other properties
... getters/setters
}
和用户输入:
<A>
<B>
<cInstanceList>
<C>
<someproperties>val</someproperties>
</C>
<C>
<someproperties>differentVal</someproperties>
</C>
</cInstanceList>
<strigValue>lalala<stirngValue>
</B>
<integerValue>42</integerValue>
</A>
缺少DataContractors
的是元数据,例如“类型”或“命名空间”等。XStream
不需要。我知道反序列化对象的类型,因此我需要编写函数:
public T Deserialize<T>(string xml);
我想要的用例:
var myDeserializedObject = Deserialize<A>(inputString);
我究竟做错了什么?您会以其他方式解决吗?
参考方案
没有序列化程序将解决键入错误;)。这使用DataContractSerializer对我有用
XML(text.xml)
<A>
<B>
<cInstanceList>
<C>
</C>
<C>
</C>
</cInstanceList>
<stringValue>lalala</stringValue>
</B>
<integerValue>42</integerValue>
</A>
班级
[DataContract(Namespace="")]
class A
{
[DataMember(Name = "B")]
private B instanceB;
[DataMember(Name = "integerValue")]
private int integerValue;
public A(B instanceB, int integerValue)
{
this.instanceB = instanceB;
this.integerValue = integerValue;
}
}
[DataContract(Namespace = "")]
class B
{
[DataMember(Name = "cInstanceList")]
private List<C> cInstanceList;
[DataMember(Name = "stringValue")]
private string stringValue;
public B(List<C> cInstanceList, string stringValue)
{
this.cInstanceList = cInstanceList;
this.stringValue = stringValue;
}
}
[DataContract(Namespace = "")]
class C
{
}
读
var dcs = new DataContractSerializer(typeof(A));
using (Stream reader = File.OpenRead("text.xml"))
{
var result = (A)dcs.ReadObject(reader);
}
如果编写,它将添加xmlns:i =“ http://www.w3.org/2001/XMLSchema-instance”,但不会有所不同,如果确实需要,可以将其删除。
休眠映射<键,设置<值>> - java我有以下表格:@Entity @Table(name = "events") Event --id --name @Entity @Table(name = "state") State --id --name @Entity @Table(name = "action") Action --id …
无法从ArrayList <String>转换为List <Comparable> - java当我写下面的代码时,编译器说 无法从ArrayList<String>转换为List<Comparable>private List<Comparable> get(){ return new ArrayList<String>(); } 但是当我用通配符编写返回类型时,代码会编译。private List&l…
合并List <T>和List <Optional <T >> - java鉴于: List<Integer> integers = new ArrayList<>(Arrays.asList( 10, 12 )); List<Optional<Integer>> optionalIntegers = Arrays.asList( Optional.of(5), Optional.em…
实例化类型<?>的泛型类 - java我正在为SCJP / OCPJP学习,并且遇到了一个对我来说很奇怪的示例问题。该示例代码实例化了两个通用集合:List<?> list = new ArrayList<?>(); List<? extends Object> list2 = new ArrayList<? extends Object>(); …
List <Dog>是List <Animal>的子类吗?为什么Java泛型不是隐式多态的? - java我对Java泛型如何处理继承/多态感到困惑。假设以下层次结构-动物(父母)狗-猫(儿童)因此,假设我有一个方法doSomething(List<Animal> animals)。根据继承和多态性的所有规则,我假设List<Dog>是List<Animal>,而List<Cat>是List<Animal&g…