Generic deserialization of an xml string

前端 未结 5 2056
名媛妹妹
名媛妹妹 2020-12-24 15:29

I have a bunch of different DTO classes. They are being serialized into an XML string at one point and shot over to client-side of the web app. Now when the client shoots

5条回答
  •  感动是毒
    2020-12-24 15:46

    You can use a generic:

        public T Deserialize(string input)
            where T : class
        {
            System.Xml.Serialization.XmlSerializer ser = new System.Xml.Serialization.XmlSerializer(typeof(T));
    
            using (StringReader sr = new StringReader(input))
                return (T)ser.Deserialize(sr);
        }
    

    If you don't know which type it will be, I assume you have a fixed number of possible types, and you could try deserializing to each one until you don't encounter an exception. Not great, but it would work.

    Or, you could inspect the start of the xml for the outer object name and hopefully be able to determine the type from there. This would vary depending on what the xml looks like.

    Edit: Per your edit, if the caller knows the type that they are passing, could they supply the fully qualified typename as a string as an additional parameter to the service?

    If so, you could do this:

        Type t = Type.GetType(typeName);
    

    and change the Deserialize method to be like this:

    public object Deserialize(string input, Type toType)
    {
        System.Xml.Serialization.XmlSerializer ser = new System.Xml.Serialization.XmlSerializer(toType);
    
        using (StringReader sr = new StringReader(input))
            return ser.Deserialize(sr);
    }
    

    However, this only gets you an object... If all of the types in question implement a common interface, you could deserialize as above but change the return type to the interface (and cast to it in the return statement)

提交回复
热议问题