我正在尝试从WCF服务返回一些JSON。该服务仅从我的数据库返回一些内容。我可以得到数据。但是,我担心JSON的格式。当前,返回的JSON格式如下:
{"d":"[{\"Age\":35,\"FirstName\":\"Peyton\",\"LastName\":\"Manning\"},{\"Age\":31,\"FirstName\":\"Drew\",\"LastName\":\"Brees\"},{\"Age\":29,\"FirstName\":\"Tony\",\"LastName\":\"Romo\"}]"}
实际上,我希望JSON的格式尽可能整洁。我相信(我可能是不正确的),以干净的JSON表示的相同结果集应如下所示:
[{
"Age": 35,
"FirstName": "Peyton",
"LastName": "Manning"
}, {
"Age": 31,
"FirstName": "Drew",
"LastName": "Brees"
}, {
"Age": 29,
"FirstName": "Tony",
"LastName": "Romo"
}]
我不知道“ d”来自哪里。我也不知道为什么要插入转义字符。我的实体如下所示:
[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;
}
}
负责返回内容的服务定义为:
[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;
}
}
如何从WCF服务返回“干净” JSON?谢谢!