简体   繁体   English

如何反序列化具有字典作为成员的自定义对象?

[英]How to Deserialize a custom object having dictionary as a member?

I need to Deserialize object having 2 fields as string and one dictionary, i tried to convert but it throwing error as " Cannot serialize member MVVMDemo.Model.Student.books of type System.Collections.Generic.Dictionary " it is doable when there is no dictionary item in but when i add that dictionary item it fail to convert. 我需要反序列化具有2个字段作为字符串和一个字典的对象,我尝试进行转换,但会Cannot serialize member MVVMDemo.Model.Student.books of type System.Collections.Generic.Dictionary错误,例如“ Cannot serialize member MVVMDemo.Model.Student.books of type System.Collections.Generic.Dictionary ”,这是可行的没有字典项目,但是当我添加该字典项目时,它无法转换。 throwing error from below line 从行下方抛出错误

XmlSerializer serializer = new XmlSerializer(typeof(Student));

Here is my class 这是我的课

public class Student
    {
        private string firstName;
        private string lastName;
        public Dictionary<string, string> books;

        public Dictionary<string, string> Books
        {
            get{return books;}
            set{books = value;}
        }
        public string FirstName
        {
            get{return firstName;}
            set
            {
                if (firstName != value)
                {
                    firstName = value;
                }
            }
        }

        public string LastName
        {
            get { return lastName; }
            set
            {
                if (lastName != value)
                {
                    lastName = value;
                }
            }
        }
    }

You can solve this with Newtonsoft.Json library. 您可以使用Newtonsoft.Json库解决此问题。 To serialize start with converting your object to json, then use DeserializeXNode method: 要序列化,首先将对象转换为json,然后使用DeserializeXNode方法:

var student = new Student()
{
    FirstName = "FirstName",
    LastName = "LastName",
    Books = new Dictionary<string, string>
    {
        { "abc", "42" },
    }
};

var json = JsonConvert.SerializeObject(student);
var xml = JsonConvert.DeserializeXNode(json, "Root");
var result = xml.ToString(SaveOptions.None);
// result is "<Root><books><abc>42</abc></books><Books><abc>42</abc></Books><FirstName>FirstName</FirstName><LastName>LastName</LastName></Root>"

To deserialize you can use SerializeXmlNode method: 要反序列化,可以使用SerializeXmlNode方法:

var input = "<Root><books><abc>42</abc></books><Books><abc>42</abc></Books><FirstName>FirstName</FirstName><LastName>LastName</LastName></Root>";
XmlDocument doc = new XmlDocument();
doc.LoadXml(input);
var json = JsonConvert.SerializeXmlNode(doc);
var template = new {Root = (Student) null};
var result = JsonConvert.DeserializeAnonymousType(json, template);
// result.Root is an instance of Student class

The reason why Dictionary is not supported by the XmlSerializer is that types such as Dictionary, HashTable, etc. needs an equality comparer which can't be serialized into XML easily. XmlSerializer不支持Dictionary的原因是Dictionary,HashTable等类型需要一个相等比较器,该比较器不能轻松地序列化为XML。 To get around this problem 为了解决这个问题

Use DataContractSerizalizer 使用DataContractSerizalizer

[DataContract]
public class Student
{
    private string firstName;
    private string lastName;

    private Dictionary<string, string> books = new Dictionary<string, string>();
    [DataMember]
    public Dictionary<string, string> Books
    {
        get => books;
        set => books = value;
    }
    [DataMember]
    public string FirstName
    {
        get { return firstName; }
        set
        {
            if (firstName != value)
            {
                firstName = value;
            }
        }
    }
    [DataMember]
    public string LastName
    {
        get { return lastName; }
        set
        {
            if (lastName != value)
            {
                lastName = value;
            }
        }
    }
}


var serializer = new DataContractSerializer(typeof(Student));
            using (var sw = new StringWriter()){
                using (var writer = new XmlTextWriter(sw))
                {
                    serializer.WriteObject(writer, student);
                    writer.Flush();
                    var xml = sw.ToString();
                }
            }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何将json字典反序列化为自定义类型 - How to deserialize a json dictionary into a custom type 如何使用自定义键将JSON反序列化为字典 - How to Deserialize JSON into dictionary with custom key 如何反序列化[JsonExtensionData]字典 <string, object> 带铸件 - How deserialize [JsonExtensionData] Dictionary<string, object> with casting 如何将字典反序列化为Xamarin Forms中的对象 - How to deserialize dictionary to an object in Xamarin Forms 如何使用 Newtonsoft 反序列化可以是数组或字典的对象? - How to deserialize object that can be an array or a dictionary with Newtonsoft? MVC - 如何在不将括号 [0] 添加到键的情况下反序列化字典? - MVC - How to deserialize a Dictionary without having brackets [0] added to the key? 序列化和反序列化字典 <int, object> 使用JavaScriptSerializer和自定义JavaScriptConverter - Serialize and deserialize Dictionary<int, object> using JavaScriptSerializer and a custom JavaScriptConverter 如何将自定义 json 反序列化为 c# 对象 - how to deserialize a custom json to c# object 如何从字典中获取对象成员的值 - How to get value of a object member from a dictionary 如何序列化/反序列化为字典 <int,List<string> &gt;`来自自定义XML - How to serialize/deserialize to `Dictionary<int,List<string>>` from custom XML
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM