Home > Software design >  c# REST Controller accepts range of names for complex object property
c# REST Controller accepts range of names for complex object property

Time:09-28

I have an endpoint with a complex object as an argument. When it is called a user supplies a JSON object.

public class ComplexObject
{
    [JsonProperty("multiNamedProperty")]
    public string MultiNamedProperty { get; set; }
    public dynamic OtherProperty { get; set; }
    public double NumberProperty { get; set; }
}

public JsonResult MethodName(ComplexObject poco)
{
    this.ServiceName.PerformLogic(poco);
} 

I want to be able to supply the endpoint a ComplexObject but have a set of names available for the property that all map like "name", "1", "banana", "n4m3", "fullName" etc.

Example expected object:

{
    thisStringCouldBeAnything: "notNullValue",
    bananaBananaTerracottaPie: { 
        banana: ["terracotta", "pie"],
        terracotta: "pie"
    },
    numberProperty: 0
}

CodePudding user response:

I suggest you use a mix of Dictionary and JDocument. But this would mean that you need to slightly restructure the expected object if you want to map it to class.

Example,

{
    properties: {
      thisStringCouldBeAnything: "notNullValue",
      bananaBananaTerracottaPie: { 
        banana: ["terracotta", "pie"],
        terracotta: "pie"
        },
      numberProperty: 0
    }
   
}

C# class

public class ComplexObject
{
    Dictionary<string,JDocument> Properties {get;set;}
}

Alternatively, you could directly use the Dictionary in the parameter without using the class,

public ActionResult GetSomething(Dictionary<string,JDocument>  properties)
{

}
  • Related