I am trying to return some JSON from a WCF service. This service simply returns some content from my database. I can get the data. However, I am concerned about the format of my JSON. Currently, the JSON that gets returned is formatted like this:
{"d":"[{\"Age\":35,\"FirstName\":\"Peyton\",\"LastName\":\"Manning\"},{\"Age\":31,\"FirstName\":\"Drew\",\"LastName\":\"Brees\"},{\"Age\":29,\"FirstName\":\"Tony\",\"LastName\":\"Romo\"}]"}
In reality, I would like my JSON to be formatted as cleanly as possible. I believe (I may be incorrect), that the same collection of results, represented in clean JSON, should look like so:
[{"Age":35,"FirstName":"Peyton","LastName":"Manning"},{"Age":31,"FirstName":"Drew","LastName":"Brees"},{"Age":29,"FirstName":"Tony","LastName":"Romo"}]
I have no idea where the “d” is coming from. I also have no clue why the escape characters are being inserted. My entity looks like the following:
[DataContract]
public class Person
{
[DataMember]
public string FirstName { get; set; }
[DataMember]
public string LastName { get; set; }
[DataMember]
public int Age { get; set; }
public Person(string firstName, string lastName, int age)
{
this.FirstName = firstName;
this.LastName = lastName;
this.Age = age;
}
}
The service that is responsible for returning the content is defined as:
[ServiceContract(Namespace = "")]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class TestService
{
[OperationContract]
[WebGet(ResponseFormat = WebMessageFormat.Json)]
public string GetResults()
{
List<Person> results = new List<Person>();
results.Add(new Person("Peyton", "Manning", 35));
results.Add(new Person("Drew", "Brees", 31));
results.Add(new Person("Tony", "Romo", 29));
// Serialize the results as JSON
DataContractJsonSerializer serializer = new DataContractJsonSerializer(results.GetType());
MemoryStream memoryStream = new MemoryStream();
serializer.WriteObject(memoryStream, results);
// Return the results serialized as JSON
string json = Encoding.Default.GetString(memoryStream.ToArray());
return json;
}
}
How do I return “clean” JSON from a WCF service?
Thank you!