Phil Murray Phil Murray - 2 months ago 6
C# Question

Json.Net serialise collection into named attributes

I am creating a Xamarin app with API calls managed by Refit and other Paul Betts libraries and was looking at serialising a collection of objects into a Json attributed array.

The question I have is how do I serialise the collection of MemberSlot objects in the MemberBooking type, using Json.Net, into the desired Json?

The names of the objects will always be numbers 1 -> 4 but some or all may not be present.

Question

Could I just change the List property in the MemberBooking object to a Dictionary and populate the string key appropriately?

Object heirarchy

public class MemberBookingRequest
{
[JsonProperty("member_booking_request")]
public MemberBooking Booking { get; set; }
}

public class MemberBooking
{
[JsonProperty("course_id")]
public int CourseId { get; set; }

[JsonProperty("date")]
public string TeeDate { get; set; }

[JsonProperty("time")]
public string TeeTime { get; set; }

[JsonProperty("slots")]
public List<MemberSlot> Slots { get; set; }
}

public class MemberSlot
{
[JsonIgnore]
public int Id { get; set; }

[JsonProperty("type")]
public BookingType Type { get; set; }

[JsonProperty("holes")]
public int Holes { get; set; }

[JsonProperty("user_id")]
public int MemberId { get; set; }
}


Current Json

{
"member_booking_request":{
"course_id":1,
"date":"2016-09-29",
"time":"09:00",
"slots":[
{
"type":"Member",
"holes":18,
"user_id":110
},
{
"type":"Member",
"holes":18,
"user_id":111
},
{
"type":"Member",
"holes":18,
"user_id":112
},
{
"type":"Member",
"holes":18,
"user_id":117
]
}
}
}


Desired Json

{
"member_booking_request":{
"course_id":1,
"date":"2016-09-29",
"time":"09:00",
"slots":{
"1":{
"type":"Member",
"holes":18,
"user_id":110
},
"2":{
"type":"Member",
"holes":18,
"user_id":111
},
"3":{
"type":"Member",
"holes":18,
"user_id":112
},
"4":{
"type":"Member",
"holes":18,
"user_id":117
}
}
}
}

Answer

You'll have to change the way you create Slots property. Assign MemberSlot.Id as key, MemberSlot itself as value when filling Slots dictionary.

public class MemberBooking
    {
        [JsonProperty("course_id")]
        public int CourseId { get; set; }

        [JsonProperty("date")]
        public string TeeDate { get; set; }

        [JsonProperty("time")]
        public string TeeTime { get; set; }

        [JsonProperty("slots")]
        public Dictionary<int,MemberSlot> Slots { get; set; }
    }