C#C
C#3y ago
LazyGuard

✅ How to parse this weird API ?

I have a very akward thing to do and I d'ont know if there is a clean way to do it.
In a REST API, there is two string fields attributeName and attributeValue (for example { "attributeName" : "isAllowed" , " attributeValue" : "true"} and { "attributeName" : "productType" , " attributeValue" : "A50"} , in the API this is modelled by the following class

N.B: the "attribute" here have nothing to do with any .NET vocabulary, it's just a name, think of it like "foo" or "bar"
public record ApiCommand
{
    public string? AttributeName {get; init;}
    public string? AttributeValue {get; init;} 
}


In my Domain I have a class with all possible properties
public record Porduct 
{
    public bool? IsAllowed {get; init;}
    public ProductType? ProductType {get; init;} // ProductType is an enum
    // There are other properties as well
}


what I need to do is, depending on the AttributeName and AttributeValue given in the API, I want to create an instance of Product which has all everything equal to null except for the property for which we were given the name and value in AttributeName and AttributeValue. (there is always a single one)

For exemple { "attributeName" : "isAllowed" , " attributeValue" : "true"} would result in a product Instance with product.IsAllowed = true and product.ProductType = null (and other fields will be null as well)

Another example, { "attributeName" : "productType" , " attributeValue" : "A50"} would result in product Instance with product.IsAllowed = null and product.ProductType = A50 (and other fields will be null as well)
Was this page helpful?