1

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?

BartoszKP
  • 34,786
  • 15
  • 102
  • 130
Y2theZ
  • 10,162
  • 38
  • 131
  • 200

1 Answers1

0

it's impossible to tweak default data contract serialization, i see following solutions

  1. change data contract serialization on Newtonsoft.Json, here is explanation On Newtonsoft.Json and create custom JsonConverter. Note you have to create JsonConverter for Result and Person. WCF's service contract isn't changed
  2. Update WCF's service contract on Stream GetPersons() and create custom JsonConverter for List<Person> Persons. This way is simpler than 1st, because the serialization process is the same
Community
  • 1
  • 1
GSerjo
  • 4,725
  • 1
  • 36
  • 55