0

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

ConsS
  • 25
  • 8
  • Possible duplicate of [Serializing a list to JSON](https://stackoverflow.com/questions/9110724/serializing-a-list-to-json) – Anas Alweish May 22 '19 at 12:21
  • so... you want to flatten the "ListaLek" on the serialized parent "StanjeZalihaLek" object? instead of having the array serialised properly? – MKougiouris May 22 '19 at 12:21
  • Not sure what you mean by "flatten" I want to serialize the StanjeZalihaLek object and within it serialize the ListaLek list with each element of the list having a serialization name of 0, 1, 2 ,3... Depending on how many items does the List have @MKougiouris – ConsS May 22 '19 at 12:30
  • 1
    By flatten i mean that normally there should be a "ListaLek" member in your output containing the serialized array, but instead you want to serialize the list elements with their index as a member name on the parent object. In order to do this you need to firstly make a new dynamic object, since one times the list might have 1 item and an other the list might have 100 items. So first look into creating a dynamic object from and then a custom serializer.... This request is rly rly weird though, what api expects a list this way!? – MKougiouris May 22 '19 at 12:36
  • Yes, exactly, I know it's weird but that's the only format the WebService accepts, any ideas how to do it that way? @MKougiouris – ConsS May 22 '19 at 12:38
  • Do you need to be able to both deserialize json into objects and serialize objects into json? – Lasse V. Karlsen May 22 '19 at 12:40
  • The deserialization part I have figured out. I get an appropriate response from the server depending on the parameter values. The only problem is List parameter as I am unable to send the request in an appropriate format. @LasseVågsætherKarlsen – ConsS May 22 '19 at 12:47
  • And by "send the request", you mean: You have .NET objects in memory and need to produce the correct Json to send to the server? – Lasse V. Karlsen May 22 '19 at 12:50
  • Yes, exactly, I have a database and in it a stored procedure from which I get my object parameter values. @LasseVågsætherKarlsen – ConsS May 22 '19 at 12:52
  • Unfortunately it didn't properly register with me that you're using DataContractJsonSerializer. I have no idea how to do it using those classes, or even if it is possible. Sorry. My now deleted answer showed a way to do it using Json.net, but if you're not using that I have no idea. – Lasse V. Karlsen May 22 '19 at 12:57
  • @UrosDimitrijevic you may want to give a look at this [post](https://www.red-gate.com/simple-talk/dotnet/c-programming/working-with-the-dynamic-type-in-c/) – Alexandre Rodrigues May 22 '19 at 13:20
  • Can you confirm whether you are using Json.NET or `DataContractJsonSerializer`? If the latter, could you switch to something else, possibly even the old `JavaScriptSerializer`? – dbc May 23 '19 at 07:25
  • 1
    I am using DataContractJsonSerializer, I cannot switch because I have a lot of classes that would need to be redone if I do that. I solved the problem I'm gonna post the solution in a second. Thank you in any case :) @dbc – ConsS May 23 '19 at 07:41

1 Answers1

0

Problem solved:

        public static byte[] Serialize(this StanjeZalihaLek data)
        {
            var sb = new StringBuilder();

            using (var tw = new System.IO.StringWriter(sb))
            {
                Newtonsoft.Json.JsonTextWriter jsonWriter = new JsonTextWriter(tw);
                jsonWriter.WriteStartObject();     

                jsonWriter.WriteRaw(JsonConvert
                                 .SerializeObject(data)
                                 .Substring(1)
                                 .TrimEnd('}'));

                jsonWriter.WriteRaw(",");

                int inx = 0;
                foreach (var item in data.ListaLek)
                {
                    var str = $"{inx++}";

                    jsonWriter.WritePropertyName(str);
                    jsonWriter.WriteRawValue(JsonConvert.SerializeObject(item));
                }
                jsonWriter.WriteEndObject();
                jsonWriter.Close();

            }

            return System.Text.Encoding.UTF8.GetBytes(sb.ToString());
        }
ConsS
  • 25
  • 8