How to consume/deserialize strapi v4 endpoints in C#?

Hey, not sure if you solved this yet but thought I’d share the way I did for anyone else probing this in the future.

create a few simple models:


    public class StrapiRoot<T> where T: AttributeWrapper {        
        [JsonProperty("data")]
        public List<DataWrapper<T>> data { get; set; }
        
        public List<T> datum {
            get
            {
                if(data == null) {
                    return new List<T>();
                }
                
                return data.Select(x => x.attributes).ToList();
            }
        }
    }

    public class DataWrapper<T> where T: AttributeWrapper {
        public int Id { get;set; }
        private T mAttributes;
        public T attributes 
        {
            get
            {
                return mAttributes;
            }

            set
            {
                value.id = Id;
                mAttributes = value;
            }
        }
    }

    public class AttributeWrapper {
        public int id { get; set; }
    }

then on your base class models, inherit from AttributeWrapper, and use StrapiRoot for your properties. Worked well for me so far. It’s a little messy, I unpack the attributes for each type using the “datum” property on root for easier access to the base models.

Hope it helps!

    public class ProductGroup : AttributeWrapper
    {
        public string ProductGroupName { get; set; }

        public string ProductGroupId { get; set; }
                
        [JsonProperty("products")]
        public StrapiRoot<Product> products { get; set; }

    }  
1 Like