I have a model with a list that I need to serialize to JSON in order to send a request to a web service.
The problem is that in my model I have a list that need to be serialized in a specific format.
My class looks like the following:
[DataContract()]
public class StanjeZalihaLek : BaseParameters
{
[DataMember(Name = "datumStanje")]
public string _datumStanja;
[DataMember(Name = "type")]
public int Type { get; set; }
[IgnoreDataMember]
public DateTime? DatumStanja { get; set; }
[IgnoreDataMember()]
public List<Lek> ListaLek { get; set; }
[OnSerializing()]
protected void OnSerializingMethod(StreamingContext context)
{
_datumStanja = DatumStanja?.ToString(FormatDate);
}
}
So all the elements are ok except the List ListaLek { get; set; } member that looks like the following:
[DataContract()]
public class Lek
{
const string FormatDate = "dd.MM.yyyy";
[DataMember(Name = "datumUlaz")]
string _datumUlaza;
[DataMember(Name = "datumRok")]
string _rokUpotrebe;
[DataMember(Name = "jkl")]
public string JedinstvenaKlasifikacijaLeka { get; set; }
[DataMember(Name = "kolicina)")]
public double Kolicina { get; set; }
[DataMember(Name = "kpp")]
public string Kpp { get; set; }
[IgnoreDataMember]
public DateTime? DatumUlaza { get; set; }
[IgnoreDataMember]
public DateTime? RokUpotrebe { get; set; }
[OnSerializing()]
protected void OnSerializingMethod(StreamingContext context)
{
_datumUlaza = DatumUlaza?.ToString(FormatDate);
_rokUpotrebe = RokUpotrebe?.ToString(FormatDate);
}
}
This is the way my serialized code is supposed to look like:
{
"idZu": "12345678",
"user": "ustanova1",
"pass": "pass1w0rd",
"type": "1",
"datumStanje": "26.02.2019",
"0": {
"jkl": "0010200",
"kolicina": "4",
"kpp": "071",
"datumUlaz": "26.02.2019",
"datumRok": " 31.12.2019"
},
"1": {
"jkl": "0010220",
"kolicina": "8",
"kpp": "071",
"datumUlaz": "26.02.2019",
"datumRok": " 31.12.2019"
},
"2": {
"jkl": "12205014",
"kolicina": "12",
"kpp": "071",
"datumUlaz": "26.02.2019",
"datumRok ": "31.12.2019"
}
}
So each new element of the list has a number as its DataMember name, with idZu, user and pass being parameters from the BaseParameters class which StanjeZalihaLek derives.
Any ideas? Thanks