1

I have class object call CustomerBase.cs with certain properties. It acts as base class for two of my other classes : Customer.cs and Vendor.cs . i.e

public class Customer: CustomerBase
public class Vendor: CustomerBase

I have a controller method as follows:

 [HttpPost("CustomerData")]
 public async Task<CustomerBase> CustomerDataAsync(CustomerBase customerBaseParam)
 { }

When this api controller is called by another web user , the Json body parameter will contain the $Type of the rootobject. It can contain vendor or Customer or just the CustomerBase. For now even when I am passing Vendor object as parameter, it is only keeping the customerBase properties for the customerBaseParam. Same with Customer object sent as Parameter. How can I change the type of customerBaseParam based on the Json body parameter that is coming in.?

Am using Newtonsoft.

2
  • The answer will be different if you are using Newtonsoft.Json or System.Text.Json. You need to specify Commented Aug 19, 2020 at 23:07
  • I am using Newtonsoft.Json Commented Aug 19, 2020 at 23:13

1 Answer 1

1

Rather than let MVC parse the JSON result for you, take in a JObject and find the field that identifies what type of JSON object that youre dealing with. This will let you decide what type to parse it as.

Note: You can design this to be apart of the MVC middle ware so that its abstracted away.

[HttpPost("CustomerData")]
public async Task<CustomerBase> CustomerDataAsync(JObject customerBaseJson)
{
    var customerBaseIdentifier = customerBaseJson["fieldNameWithinTheJsonPayload"];

    //This should really be a strategy pattern to adhere to the SOLID open close principle.
    switch(customerBaseIdentifier) {
        case "type 1":
            var type1Object = JsonConvert.Deserialize<Type1>(customerBaseJson);
            break;
        case ...
    }
}


Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.