anwar ul haque
asked on
How to return complex types like Generics(List<KeyValuePair<string,string>> or Dictionary<string,string>) from WebMethod
I am currently working on ASP.NET Web Services and I want to return complex types like System.Collection.Generic class. I tried to return Dictionary<string,string> but this gave me exception. then I tried to return List<KeyValuePair<string,s tring> objKeyValuePair> but it didnt solve my problem. Can you tell me how can I return complex types. I dont want to serialize my data as this is not my requirement. Thanks in advance for any help or suggestion.
As far as I can tell, response of a web service is always in XML, that is why they are called XML Web Services, that means types that are to be returned have to be serializable.
Sorry submitted by mistake. Here is it again:
Note:You could try to make it a Generic class so that it would work with all types of KeyValuePair<t1, t2>. I'm not sure how it would work though.
Note:You could try to make it a Generic class so that it would work with all types of KeyValuePair<t1, t2>. I'm not sure how it would work though.
[Serializable]
public class KeyValuePairSerializable
{
private string _key,_value
public KeyValuePairSerializable() //Required for serialization
{
}
public KeyValuePairSerializable(KeyValuePair<string, string> value)
{
this._key=value.Key;
this._value=value.Value;
}
public string Key {
get {return _key;}
set {_key=value;}
}
public string Value {
get {return _value;}
set {_value=value;}
}
}
I just did a test and List<T> is serializable, but I could not get List<KeyValuePair<string,s tring>> to work. Dictionary<string,string> is NOT XML serializable because it implements IDictionary. But I got List<KeyValuePairSerializa ble> to work.
[WebMethod]
public List<KeyValuePairSerializable> HelloWorld()
{
Dictionary<string, string> hello = new Dictionary<string, string>();
hello.Add("hello", "world");
hello.Add("world", "hello");
List<KeyValuePairSerializable> list=new List<KeyValuePairSerializable>();
foreach (KeyValuePair<string, string> item in hello)
{
list.Add(new KeyValuePairSerializable(item));
}
return list;
}
ASKER
How can I use this class within my web service. My method's return value is List<KeyValuePair<string,s tring>>.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Thank you mates, finally I got desired results.
ASKER
while I was searching for the solution I could not find the answer so that's why I asked my question here.For me points are not issue I got solution and I'm very happy and thakful to these gentlemen.
Thanks.
Thanks.
Open in new window