Let's say I've got a custom type that looks like this:
[DataContract]
public class CompositeType
{
[DataMember]
public bool HasPaid
{
get;
set;
}
[DataMember]
public string Owner
{
get;
set;
}
}
and a WCF REST interface that looks like this:
[ServiceContract]
public interface IService1
{
[OperationContract]
Dictionary<string, CompositeType> GetDict();
}
then how do I get my implementation of that method to return a JSON object that looks like this...
{"fred":{"HasPaid":false,"Owner":"Fred Millhouse"},"joe":{"HasPaid":false,"Owner":"Joe McWirter"},"bob":{"HasPaid":true,"Owner":"Bob Smith"}}
I do not want it to look like this:
[{"Key":"fred","Value":{"HasPaid":false,"Owner":"Fred Millhouse"}},{"Key":"joe","Value":{"HasPaid":false,"Owner":"Joe McWirter"}},{"Key":"bob","Value":{"HasPaid":true,"Owner":"Bob Smith"}}]
Ideally I would prefer not to have to alter the return type of the method.
I have tried many different approaches but cannot find a solution that works. Annoyingly, it is easy to produce the right-shaped JSON object structure in one line with Newtonsoft.Json
:
string json = JsonConvert.SerializeObject(dict);
where dict
is defined as:
Dictionary<string, CompositeType> dict = new Dictionary<string, CompositeType>();
dict.Add("fred", new CompositeType { HasPaid = false, Owner = "Fred Millhouse" });
dict.Add("joe", new CompositeType { HasPaid = false, Owner = "Joe McWirter" });
dict.Add("bob", new CompositeType { HasPaid = true, Owner = "Bob Smith" });
but I do not want to return a string from my WCF method. This is because it conceals the real type being returned; and also because WCF serializes the string as well, resulting in escaped double quotes and other ugliness that makes it harder for non-.Net REST clients to parse.
See Question&Answers more detail:
os