Returning a common object without knowing the type?

I'm still pretty new to programming, and I was tasked with creating a WebHook consumer that uses a JSON string string, parses the JSON in the object, which will be passed to the handler for processing. JSON does as follows:

{
   "id":"1",
   "created_at":"2017-09-19T20:41:23.093Z",
   "type":"person.created",
   "object":{
      "id":"person1",
      "created_at":"2017-09-19T20:41:23.076Z",
      "updated_at":"2017-09-19T20:41:23.076Z",
      "firstname":"First",
      ...
   }
}

Any object can be an internal object, so I thought it would be a great opportunity to use generics and build my class like this:

public class WebHookModel<T> where T : class, new()
{
    [JsonProperty(PropertyName = "id")]
    public string Id { get; set; }

    [JsonProperty(PropertyName = "created_at")]
    public DateTime CreatedAt { get; set; }

    [JsonProperty(PropertyName = "type")]
    public string Type { get; set; }

    [JsonProperty(PropertyName = "object")]
    public T Object { get; set; }

    [JsonIgnore]
    public string WebHookAction
    {
        get
        {
            return string.IsNullOrEmpty(Type) ? string.Empty : Type.Split('.').Last();
        }
    }
}

Then the following interface is created:

public interface IWebHookModelFactory<T> where T : class, new()
{
   WebHookModel<T> GetWebHookModel(string type, string jsonPayload);
}

That I do not understand, how should I implement the Factory class without knowing what type is at compile time?

After working a little with the model, I changed it to an abstract class with an abstract object T so that it could be defined by a derived class.

public abstract class WebHookModel<T> where T : class, new()
{
    [JsonProperty(PropertyName = "id")]
    public string Id { get; set; }

    [JsonProperty(PropertyName = "created_at")]
    public DateTime CreatedAt { get; set; }

    [JsonProperty(PropertyName = "type")]
    public string Type { get; set; }

    [JsonProperty(PropertyName = "object")]
    public abstract T Object { get; set; }

    [JsonIgnore]
    public string WebHookAction
    {
        get
        {
            return string.IsNullOrEmpty(Type) ? string.Empty : Type.Split('.').Last();
        }
    }
}

public PersonWebHookModel : WebHookModel<Person>
{
    public override Person Object { get; set; }
}

, , . , , , , , . case case?

public interface IWebHookFactory<TModel, TJsonObject> 
    where TJsonObject : class, new()
    where TModel : WebHookModel<TJsonObject>
{
    TModel GetWebHookModel(string type, string jsonPayload);
}

, .

public interface IWebHookService<TModel, TJsonObject>
    where TJsonObject : class, new()
    where TModel : WebHookModel<TJsonObject>
{
    void CompleteAction(TModel webHookModel);
}

public abstract class BaseWebhookService<TModel, TJsonObject> : IWebHookService<TModel, TJsonObject>
        where TJsonObject : class, new()
        where TModel : WebHookModel<TJsonObject>
{
    public void CompleteAction(TModel webHookModel)
    {
        var self = this.GetType();
        var bitWise = System.Reflection.BindingFlags.IgnoreCase
                        | System.Reflection.BindingFlags.Instance
                        | System.Reflection.BindingFlags.NonPublic;

        var methodToCall = self.GetMethod(jsonObject.WebHookAction, bitWise);
        methodToCall.Invoke(this, new[] { jsonObject });
    }

    protected abstract void Created(TModel webHookObject);

    protected abstract void Updated(TModel webHookObject);

    protected abstract void Destroyed(TModel webHookObject);
}

public class PersonWebHookService : BaseWebHookService<PersonWebHookModel, Person>
{
    protected override void Created(PersonWebHookModel webHookModel)
    {
        throw new NotImplementedException();
    }

    protected override void Updated(PersonWebHookModel webHookModel)
    {
        throw new NotImplementedException();
    }

    protected override void Destroyed(PersonWebHookModel webHookModel)
    {
        throw new NotImplementedException();
    }
}
+4
1

: 1. - - . 2. - JSON #.
IE, "person.created", "- > " Person ".
, JSON.Net . , ... - , .

, :

abstract class WebhookPayload // Note this base class is not generic! 
{
    // Common base properties here 

    public abstract void DoWork();
}

abstract class PersonPayload : WebhookPayload
{
    public override void DoWork()
    {
        // your derived impl here 
    }
}

:

    static Dictionary<string, Type> _map = new Dictionary<string, Type>
    {
        { "person.created", typeof(PersonPayload)}
    }; // Add more entries here 

    public static WebhookPayload Deserialize(string json)
    {
        // 1. only parse once!
        var jobj = JObject.Parse(json); 

        // 2. get the c# type 
        var strType = jobj["type"].ToString(); 

        Type type;
        if (!_map.TryGetValue(strType, out type))
        {
            // Error! Unrecognized type
        }

        // 3. Now deserialize 
        var obj = (WebhookPayload) jobj.ToObject(type);
        return obj;
    }
+2

Source: https://habr.com/ru/post/1686055/


All Articles