Background used today: C# Json serialization and deserialization
Deserialization The following error message appeared.
System.Runtime.Serialization.SerializationException: 数据协定类型“TestEntity”无法反序列化,因为未找到必需的数据成员“multipleChoice, runTimeDisplayColumns”。 在 System.ComponentModel.ReflectPropertyDescriptor.SetValue(Object component, Object value)
The specific reason is: I added a new one to the deserialized entity class Two attributes:
private bool multipleChoice; /// <summary> /// 帮助引擎是否允许多选 /// </summary> [XmlIgnore] [Browsable(false)] public bool MultipleChoice { get { return multipleChoice; } set { multipleChoice = value; } } private string runTimeDisplayColumns; /// <summary> /// 帮助引擎运行时显示的列 /// </summary> [XmlIgnore] [Browsable(false)] public string RunTimeDisplayColumns { get { return runTimeDisplayColumns; } set { runTimeDisplayColumns = value; } }
When using the previously saved Json string to deserialize, the two new attributes have no corresponding values. So the above error was reported.
Solution:
[DataContract] public class TestEntity { private bool multipleChoice; /// <summary> /// 帮助引擎是否允许多选 /// </summary> [XmlIgnore] [Browsable(false)] [DataMember(IsRequired = false)] public bool MultipleChoice { get { return multipleChoice; } set { multipleChoice = value; } } private string runTimeDisplayColumns; /// <summary> /// 帮助引擎运行时显示的列 /// </summary> [XmlIgnore] [Browsable(false)] [DataMember(IsRequired = false)] public string RunTimeDisplayColumns { get { return runTimeDisplayColumns; } set { runTimeDisplayColumns = value; } } }
Passed The DataMember(IsRequired = false) property represents this property and is not required. In this way, it is guaranteed that during deserialization, even if the definition of the attribute is missing in the JSON string, it can be deserialized normally.
Small note:
##Add DataMember(IsRequired = false), the [DataContract] mark must be added to the corresponding class.
The above is the above content. For more related content, please pay attention to the PHP Chinese website (m.sbmmt.com)! For more related content, please pay attention to the PHP Chinese website (m.sbmmt.com)!