【发布时间】:2021-09-15 03:27:08
【问题描述】:
我有问题如何创建一个类定义来序列化和反序列化具有相同结果的对象。
这个类定义:
/// <remarks/>
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://hl7.org/fhir")]
public partial class PatientName
{
private PatientNameFamily familyField;
private PatientNameGiven givenField;
/// <remarks/>
public PatientNameFamily family
{
get
{
return this.familyField;
}
set
{
this.familyField = value;
}
}
/// <remarks/>
public PatientNameGiven given
{
get
{
return this.givenField;
}
set
{
this.givenField = value;
}
}
}
/// <remarks/>
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://hl7.org/fhir")]
public partial class PatientNameFamily
{
private string valueField;
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string value
{
get
{
return this.valueField;
}
set
{
this.valueField = value;
}
}
}
/// <remarks/>
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://hl7.org/fhir")]
public partial class PatientNameGiven
{
private string valueField;
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string value
{
get
{
return this.valueField;
}
set
{
this.valueField = value;
}
}
}
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://hl7.org/fhir")]
public partial class PatientNameFamily
{
private string valueField;
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string value
{
get
{
return this.valueField;
}
set
{
this.valueField = value;
}
}
}
/// <remarks/>
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://hl7.org/fhir")]
public partial class PatientNameGiven
{
private string valueField;
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string value
{
get
{
return this.valueField;
}
set
{
this.valueField = value;
}
}
}
将正确的序列化为 XML,如下所示:
<name>
<family value="Senior"/>
<given value="Sylwester"/>
</name>
但是当尝试反序列化 JSON 时: {\"family\": \"Seniorka\",\"given\": [ \"Sylwia\" ]} ]
我有例外:
将值“Seniorka”转换为类型“PlatformaP1ATD.ZM.PatientNameFamily”时出错,当然我可以将类定义更改为字符串和字符串数组,但我不想让两个类从 JSON 序列化为 xml 和反序列化。
知道如何将字符串值转换为嵌套类型吗?
【问题讨论】:
标签: c# json xml serialization deserialization