'How to populate an object inside of an object and call it whenever in C#
So I have an object (Location)
This Location Object contains what is a Location
I have also added another object that is a Venue on the last line.
namespace EngageServicesEditor.Core
{
public class Location
{
public string id { get; set; }
public string venueId { get; set; }
public string companyId { get; set; }
public string locationName { get; set; }
public Venue Venue { get; set; }
}
}
This is how I currently populate my object of Location
public IEnumerable<Location> GetLocations()
{
var response = connection.Api.GetAsync("/api/v1/Locations").Result;
var content = response.Content.ReadAsStringAsync().Result;
var actual = JsonSerializer.Deserialize<List<Location>>(content);
return actual;
}
NEW as requested
The JSON output in the content variable is
[
{
"id": "1",
"venueId": "1",
"companyId": "1",
"locationName": "LocationOne"
},
{
"id": "2",
"venueId": "2",
"companyId": "2",
"locationName": "LocationTwo"
},
Ect...
]
Venue Object only contains ID, companyID, venueName.
I have a different class for API connection string and I also use Interfaces to be able to access data around my program.
I know this is possible but I do not have a clue for some reason of how to populate that object and call it whenever I need it.
My aim for this is to be able to populate my Location Object and if I need some Venue data I also want to populate the Venue object within the Location object so I have access to the venue data whenever I'm using the Location.
Now I might be wrong here but I think that is possible to do it and it should work as I explained it. But I have no clue how to even after some research.
If anyone got any documentation on this for me to read please do link it down below I will make sure to understand it and see if I can get it to work.
Solution 1:[1]
Your JSON only contains the ID as string not the all object data!...
So you have to serialize to string. Then retrieve the value of all object data wherever you store it, maybe as following
public class Location
{
public string id { get; set; }
public string venueId { get; set; }
public string companyId { get; set; }
public string locationName { get; set; }
public Venue Venue
{
get
{
if(string.IsNullOrEmpty(VenewId)) return null;
// Retrieve the object with the corresponding Id
return new Venue(); // << From your Venue List
}
}
}
Or if you have a control on your JSON, you can use your code but change the JSON Format to be look like
[
{
"id": "1",
"locationName": "LocationOne",
"Venue": {
"venueId": "1",
"companyId": "1",
"venueName": "name of it"
}
},
{
"id": "2",
"locationName": "LocationTwo",
"Venue": {
"venueId": "2",
"companyId": "2",
"venueName": "name of it"
}
}
]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | marc_s |
