c# - How to return Dictionary<complexType,int> with WebAPI -


i'm providing webapi 2 endpoint done in way:

my controller simply:

 public idictionary<myclass, int> getmyclasses(string id)  {     dictionary<myclasses, int> sample = new dictionary<myclasses, int>();      sample.add(new myclasses()     {        property1 = "aaa",        property2 = 5,        property3 = 8     },10);      return sample;  } 

the structure of myclass is:

public class myclass {    string property1 {get;set;}    int property2 {get;set;}    int property3 {get;set;} } 

when run webservice, helper webpage shows me expected outputs are:

{ "mynamespace.myproject.myclass": 1 } 

on other hand xml sample i'd (except want json, not xml):

<arrayofkeyvalueofmyclassintl85fhlc_p xmlns:i="http://www.w3.org/2001/xmlschema-instance" xmlns="http://schemas.microsoft.com/2003/10/serialization/arrays">   <keyvalueofmyclassintl85fhlc_p>     <key xmlns:d3p1="http://schemas.datacontract.org/2004/07/mynamespace.myproject.myclass">       <d3p1:property1>sample string 4</d3p1:property1>       <d3p1:property2>8</d3p1:property2>       <d3p1:property3>5</d3p1:property3>     </key>     <value>1</value>   </keyvalueofmyclassintl85fhlc_p> </arrayofkeyvalueofmyclassintl85fhlc_p > 

i ran endpoint postman , confirms returned value 1 previewed webapi out of box page.

why json "wrong" , xml done (i mean contains data)?

updated:

i expected myclass serialized in json this:

{   "property1": "sample string 4",   "property2": 8,   "property3": 5 } 

this should structure of key of dictionary, in xml representation.

thanks

this kind of hacky, had success converting dictionary list object before running through jsonconvert. check out:

idictionary<myclass,int> dict = new dictionary<myclass, int>(); myclass classy = new myclass() { value = value }; dict.add(classy, 5); string json = jsonconvert.serializeobject(dict); //<--- returns [{myclass: 5}], boo 

whereas . . .

string json = jsonconvert.serializeobject(dict.tolist()); //<--- returns [{key: blah blah blah, value: 5}], nice 

hope helps.


Comments

Popular posts from this blog

OpenCV OpenCL: Convert Mat to Bitmap in JNI Layer for Android -

android - org.xmlpull.v1.XmlPullParserException: expected: START_TAG {http://schemas.xmlsoap.org/soap/envelope/}Envelope -

python - How to remove the Xframe Options header in django? -