0

I was trying to serialize a KeyValue "Array" to send it via PUT over http to my asp.net webserver.

The function in Angular looks like this:

SortAboutUs(data : KeyValue<number,number>[]) {
    this.dataTransmitter.Put(this.apiUrl+'/api/aboutus/sort', data);    
}

and if I debug the following data container then it looks like this:

Datacontainer

I have the following in my .net core Webserver's Controller

[HttpPut("[action]")]
public ActionResult<bool> Sort(IList<KeyValuePair<int, int>> dto)
{
    return Ok(_aboutUsService.Sort(dto));
}

However i get the following error when trying to send it via PUT:

The JSON value could not be converted to System.Collections.Generic.List`1[System.Collections.Generic.KeyValuePair`2[System.Int32,System.Int32]]. Path: $[0] | LineNumber: 0 | BytePositionInLine: 8.

Weird thing is that I've already used the same technique in another older version of .net core and there everything seems to work.

I also noticed that since .net core 3.1 the KeyValue in C# changed to KeyValuePair but in older versions of .net core it was KeyValue.

Does that have to do something with my related error?

And how can I serialize the KeyValue from Angular so that my Webserver can read it?

Fy Z1K
  • 618
  • 1
  • 7
  • 21

2 Answers2

0

Your object should go like :-

[
 {
   4: 0
 },
 {
   5: 1
 },
 {
   6: 2
 }
]
Aakash Garg
  • 10,649
  • 2
  • 7
  • 25
  • I changed the object like you suggested but I still get the same error. What is the Type declaration of this object in the controller methods param? – Fy Z1K Jun 18 '20 at 15:43
  • hey apologies your older format works fine, but should you use Dictionary instead of keyvaluepair in .net? – Aakash Garg Jun 18 '20 at 15:52
  • Thank you for your reply. I tried using IDictionary before but I got the Error that "Dictionary is not suppoorted", for whatsoever reason. Weird thing is that this same technique with IList> worked in an older version (v2.2) of .netcore but it seems to refuse to work since .net core 3.1. – Fy Z1K Jun 18 '20 at 15:58
  • write a custom converter like given here :- https://stackoverflow.com/questions/21021655/json-serialize-listkeyvaluepairstring-object/21022139 – Aakash Garg Jun 18 '20 at 15:59
0

I was able to solve the Issue by creating my own KeyValue Class like so:

public class KeyValue<K,V>
{
    public K Key { get; set; }
    public V Value { get; set; }
}

after this my Controller Method now looks like this:

[HttpPut("[action]")]
public ActionResult<bool> Sort([FromBody] IList<KeyValue<int, int>> dto)
{
    return Ok(_aboutUsService.Sort(dto));
}

Thanks to this approach the Controller was able to receive the sent Array of KeyValue over PUT from Angular to my Webserver...enter image description here

Fy Z1K
  • 618
  • 1
  • 7
  • 21