I am working on a WCF web services project.
I have a list of persons with their age that I need to return as a JSON. For that I am doing the following:
This is my service function:
[OperationContract]
[WebInvoke(
Method = "GET",
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Bare,
UriTemplate = "GetPersons")]
Result GetPersons();
I have the Person
Class:
[DataContract]
public class Person
{
[DataMember(Name = "ID")]
public int ID { get; set; }
[DataMember(Name = "Name")]
public string Name { get; set; }
[DataMember(Name = "Age")]
public int Age{ get; set; }
}
And a class Result
:
[DataContract]
public class Result
{
[DataMember(Name = "Persons")]
public List<Person> Persons{ get; set; }
}
When returning the Result
class I am getting this JSON form:
{"Persons":[{"Name" : "Tom", "Age" : 5 } , {"Name" : "Kate", "Age" : 8 }]}
Is there a way I can have this structure:
{"Persons":{"Tom" : 5, "Kate" : 8 }}
?
Basically I want the person names to be the key for the age.
I tried using a Dictionary<string, int>
instead of the Person
class but I am getting the following:
{"Persons":[{"Key" : "Tom", "Value" : 5 } , {"Key" : "Kate", "Value" : 8 }]}
How can I get the wanted JSON form? Is there a way to do it by using the WCF built in serialization or will I have to manually construct the string?