jeudi 25 juillet 2019

Deserialize JSON object to specific instance created on the fly in run time by string name of the class

Working on several RDLC, in C# VS2017, I found that I need to send specific instances of my own objects. Avoiding the struggling with a large switch, I want to know if there is some way to create an instance on the run time by the class name

I've a dummy fiddle in order to test it, but can't complete it: https://dotnetfiddle.net/eMwleG

My code until now, after a lot of test and answers from SO, from JSON Conversion to Casting types and using reflection:

using System;
using System.Collections.Generic;
using Newtonsoft.Json;
using System.Reflection;                    
public class Program
{
    public static T GetObjectAs<T>(object source, T destinationType)
   where T: class
{
     return Convert.ChangeType(source, typeof(T)) as T;
}

    public static void Main()
    {
        //From Object to string
        var nameMessage = new MessageWrapper<Name>();
        nameMessage.Message = new Name {First="Bob", Last = "Smith"};
        string serialized = JsonConvert.SerializeObject(nameMessage);

        //From String to Object
        var deserialized = JsonConvert.DeserializeObject<MessageWrapper>(serialized);
        var messageType = Type.GetType(deserialized.MessageType);

        var message = JsonConvert.DeserializeObject(Convert.ToString(deserialized.Message), messageType);

        Name myname = GetObjectAs(message, System.Reflection.Assembly.GetExecutingAssembly().CreateInstance("Name"));

        //Name myname =  Convert.ChangeType(message,messageType) as Name;
        Console.WriteLine(myname.First);

    }
}

public class MessageWrapper<T>
{
    public string MessageType { get { return typeof(T).FullName; } }
    public T Message { get; set; }
}

public class MessageWrapper
{
    public string MessageType { get; set; }
    public object Message { get; set; }
}


public class Name
{
    public string First;
    public string Last;
}

So my question is:

How can create an specific instance of my object "Name" in run time and assign it from an objected casted by a dynamic conversion?

Please don't try to cover the logic of the example, is a dummy example to do something. I can accept answers and ideas of course, with the same spirit, take in consideration I don't "know" the class called to be casted.





Aucun commentaire:

Enregistrer un commentaire