I am trying to serialize this model
public class Rootobject
{
public Los los { get; set; }
public int Id { get; set; }
}
public class Los
{
[JsonConverter(typeof(DictionaryToJsonObjectConverter))]
public Dictionary<DateTime, List<Item>> items { get; set; }
}
public class Item
{
public string currency { get; set; }
public int guests { get; set; }
public int[] price { get; set; }
}
and I am getting this
{
"los": {
"items": {
"2020-01-10T00:00:00+01:00": [
{
"currency": "EUR",
"guests": 1,
"price": [
443
]
}
],
"2020-01-11T00:00:00+01:00": [
{
"currency": "EUR",
"guests": 1,
"price": [
500
]
}
]
}
},
"Id": 1
}
and I would like to get this response
{
"los": {
"2020-01-10T00:00:00+01:00": [
{
"currency": "EUR",
"guests": 1,
"price": [
443
]
}
],
"2020-01-11T00:00:00+01:00": [
{
"currency": "EUR",
"guests": 1,
"price": [
500
]
}
]
},
"Id": 1}
I would like to use attributes to achieve this, but I am not sure how.
I tried writing my custom json converter, but that didnt do much
public class DictionaryToJsonObjectConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return typeof(IDictionary<DateTime, List<Item>>).IsAssignableFrom(objectType);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
throw new NotImplementedException();
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
writer.WriteRawValue(JsonConvert.SerializeObject(value, Formatting.Indented));
}
}
The issue in your code is the way how you are populating dictionary. Your current class structure is:
RootObject
|
|
|--los (with json proerty set to display)
|
|
|--- items dictionary
What you need is this:
RootObject
|
|
|-- items dictionary los (either rename the property name to los or use JsonProperty to use los)
So, in order to get the required result, please emove the class Los and move the below line directly under RootObject:
public Dictionary<DateTime, List<Item>> items { get; set; }
and rename items as los.
So, after the changes, So, your Rootobject object looks like below:
public class Rootobject
{
// public Los los { get; set; }
// I don't think you need this converter unless you have special logic
[JsonConverter(typeof(DictionaryToJsonObjectConverter))]
public Dictionary<DateTime, List<Item>> los { get; set; }
public int Id { get; set; }
}