如何从 WCF 服务返回干净的 JSON? [英] How do I return clean JSON from a WCF Service?

查看:30
本文介绍了如何从 WCF 服务返回干净的 JSON?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从 WCF 服务返回一些 JSON.该服务只是从我的数据库中返回一些内容.我可以得到数据.但是,我担心我的 JSON 的格式.目前,返回的 JSON 格式如下:

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"}]"} 

实际上,我希望我的 JSON 格式尽可能干净.我相信(我可能不正确),以干净的 JSON 表示的相同结果集合应该如下所示:

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"
}]

我不知道d"是从哪里来的.我也不知道为什么要插入转义字符.我的实体如下所示:

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;
    }
}

如何从 WCF 服务返回干净"的 JSON?谢谢!

How do I return "clean" JSON from a WCF service? Thank you!

推荐答案

将 GetResults 的返回类型更改为 List.
消除用于将 List 序列化为 json 字符串的代码 - WCF 会自动为您执行此操作.

Change the return type of your GetResults to be List<Person>.
Eliminate the code that you use to serialize the List to a json string - WCF does this for you automatically.

使用您对 Person 类的定义,此代码适用于我:

Using your definition for the Person class, this code works for me:

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"}]

(全部在一行)

我也在方法上使用了这个属性:

I also used this attribute on the method:

[WebInvoke(Method = "GET",
           RequestFormat = WebMessageFormat.Json,
           ResponseFormat = WebMessageFormat.Json,
           UriTemplate = "players")]

WebInvoke with Method="GET" 与 WebGet 相同,但由于我的一些方法是 POST,我使用所有 WebInvoke 以保持一致性.

WebInvoke with Method= "GET" is the same as WebGet, but since some of my methods are POST, I use all WebInvoke for consistency.

UriTemplate 设置方法可用的 URL.所以我可以做一个GEThttp://myserver/myvdir/JsonService.svc/players 就可以了.

The UriTemplate sets the URL at which the method is available. So I can do a GET on http://myserver/myvdir/JsonService.svc/players and it just works.

还要检查 IIRF 或其他 URL 重写器以摆脱 URI 中的 .svc.

Also check out IIRF or another URL rewriter to get rid of the .svc in the URI.

这篇关于如何从 WCF 服务返回干净的 JSON?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆