Is there a way to serialize the attributes property below with a name/value property in .NET? I can't seem to find a good way to serialize the class to the attributes property with values like, sport, venue, city, province, and others.
{
"uid": "uuid",
"object": "live_event",
"title": "Event Name",
"event_start": "2022-10-10T12:00:00:000Z",
"timezone": "America/Denver",
"external_id": "some_external_user_generated_id",
"container_uid": "02f8270a-8662-45b3-898a-c915a68cdf87",
"description": "Description of the event",
"short_description": "Short description of the event",
"attributes": [
{ "sport": "Soccer" },
{ "venue": "New Park" },
{ "city": "Calgary" },
{ "province": "Alberta" },
{ "teams": ["teamA", "teamB"] }
]
}
Class
public class CreateEventRequest : VidFlexRequest, ISaveEventRequest
{
[JsonProperty("uid", NullValueHandling = NullValueHandling.Ignore)]
public string UId { get; set; }
[JsonProperty("title")]
public string Title { get; set; }
[JsonProperty("event_start")]
public string EventStart { get; set; }
[JsonProperty("timezone")]
public string TimeZone { get; set; }
[JsonProperty("external_id")]
public string ExternalId { get; set; }
[JsonProperty("description", NullValueHandling = NullValueHandling.Ignore)]
public string Description { get; set; }
[JsonProperty("short_description", NullValueHandling = NullValueHandling.Ignore)]
public string ShortDescription { get; set; }
}
CodePudding user response:
The easiest ( but not the best) way would be define your attributes property as
[JsonProperty("attributes")]
public Dictionary<string,object>[] Attributes { get; set; }
the better way is to use JsonConstructor
public class CreateEventRequest
{
[JsonProperty("uid", NullValueHandling = NullValueHandling.Ignore)]
public string UId { get; set; }
.....
public List <KeyValuePair<string,object>> Attributes { get; set; }
[JsonConstructor]
public CreateEventRequest(JArray attributes)
{
Attributes= attributes.Select(a => new KeyValuePair<string, object>(
((JObject)a).Properties().First().Name,((JObject)a).Properties().First().Value )).ToList();
}
}