wcf - 如何从WCF服务返回干净的JSON?

我正试图从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服务返回“clean”json?
谢谢您!


最佳答案:

将getresults的返回类型更改为List<Person>
消除用于将列表序列化为JSON字符串的代码—wcf会自动为您执行此操作。
使用您对Person类的定义,此代码适用于我:

public List<Person> GetPlayers()
{
    List<Person> players = new List<Person>();
    players.Add(new  Person { FirstName="Peyton", LastName="Manning", Age=35 } );
    players.Add(new  Person { FirstName="Drew", LastName="Brees", Age=31 } );
    players.Add(new  Person { FirstName="Brett", LastName="Favre", Age=58 } );

    return players;
}

结果:
[{"Age":35,"FirstName":"Peyton","LastName":"Manning"},  
 {"Age":31,"FirstName":"Drew","LastName":"Brees"},  
 {"Age":58,"FirstName":"Brett","LastName":"Favre"}]

(全部在一条线上)
我在方法上也使用了这个属性:
[WebInvoke(Method = "GET",
           RequestFormat = WebMessageFormat.Json,
           ResponseFormat = WebMessageFormat.Json,
           UriTemplate = "players")]

webInvoke with method=“get”与webget相同,但由于我的一些方法是post,所以为了一致性,我使用了所有webInvoke。
uritemplate设置方法可用的URL。所以我可以上车
http://myserver/myvdir/JsonService.svc/players而且它只是起作用。
还可以查看iirf或另一个URL重写器来除去URI中的.svc。

评论