2

I have an API controller which is calling a 3rd party API, and then deserializing it via two API models to C#. I am using JsonObject and JsonProperties in the API models.

Now I need to gather properties from both models in my response to the client. In the controller I have created two C# objects, each one getting info from the API models. I want to create a object holding specific properties from both objects. Can anyone advise on the best practice to accomplish this?

var personJson = await personResponse.Content.ReadAsStringAsync();
var companyJson = await companyResponse.Content.ReadAsStringAsync();

var UserObject = JsonConvert.DeserializeObject<Person.RootObject>(personJson);
var CompanyObject = JsonConvert.DeserializeObject<Company.RootObject>(companyJson);
2
  • 3
    Make a third model that is an amalgamation of the two data models. This is usually called a viewmodel in an MVC context, since you are using Web.API think of it like your API's model Commented Sep 28, 2018 at 14:11
  • Which two objects are you indicating here in your code? Commented Sep 28, 2018 at 14:19

1 Answer 1

2

You could create a class for the data that you need to return and fill it, but in many cases it suffices to use an anonymous object which the framework will then serialize for you. Example:

return new
{
    UserId = UserObject.Id,
    UserFullname = UserObject.FirstName + " " + UserObject.LastName,
    CompanyId = CompanyObject.Id,
    CompanyName = CompanyObject.Name
};

You can take this as far as you need, even including arrays, dictionaries, lists, nested (sub)objects, etc.

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

1 Comment

thank you peter, this seems to be what i was looking for! if i wanted to make a class to hold the specific data, how would I specify which model(Company or User in my case) to gather data from? I am using [JsonObject] and [JsonProperty] in the Company and User-models

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.