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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2086666/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 17:24:15  来源:igfitidea点击:

How do I return clean JSON from a WCF Service?

wcfjson

提问by user208662

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:

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

{"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:

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

[{
  "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:

我不知道“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;
    }
}

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!

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

采纳答案by Cheeso

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.

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

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

使用您对 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;
}

results:

结果:

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

(All on one line)

(全部在一行)

I also used this attribute on the method:

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

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

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

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

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

UriTemplate 设置方法可用的 URL。所以我可以做一个 GET http://myserver/myvdir/JsonService.svc/players并且它只是有效。

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

还可以查看 IIRF 或其他 URL 重写器以去除 URI 中的 .svc。

回答by JeremyWeir

If you want nice json without hardcoding attributes into your service classes,

如果您想要漂亮的 json,而无需将属性硬编码到您的服务类中,

use <webHttp defaultOutgoingResponseFormat="Json"/>in your behavior config

<webHttp defaultOutgoingResponseFormat="Json"/>你的行为的配置

回答by user517301

This is accomplished in web.config for your webservice. Set the bindingBehavior to <webHttp> and you will see the clean JSON. The extra "[d]" is set by the default behavior which you need to overwrite.

这是在 web.config 中为您的 web 服务完成的。将 bindingBehavior 设置为 <webHttp>,您将看到干净的 JSON。额外的“[d]”由您需要覆盖的默认行为设置。

See in addition this blogpost: http://blog.clauskonrad.net/2010/11/how-to-expose-json-endpoint-from-wcf.html

另外参见这篇博文:http: //blog.clauskonrad.net/2010/11/how-to-expose-json-endpoint-from-wcf.html

回答by KhalilG

I faced the same problem, and resolved it by changing the BodyStyle attribut value to "WebMessageBodyStyle.Bare" :

我遇到了同样的问题,并通过将 BodyStyle 属性值更改为 "WebMessageBodyStyle.Bare" 来解决它:

[OperationContract]
[WebGet(BodyStyle = WebMessageBodyStyle.Bare, RequestFormat = WebMessageFormat.Json,
        ResponseFormat = WebMessageFormat.Json, UriTemplate = "GetProjectWithGeocodings/{projectId}")]
GeoCod_Project GetProjectWithGeocodings(string projectId);

The returned object will no longer be wrapped.

返回的对象将不再被包装。

回答by Osama Ibrahim

In your IServece.cs add the following tag : BodyStyle = WebMessageBodyStyle.Bare

在您的 IServece.cs 中添加以下标签: BodyStyle = WebMessageBodyStyle.Bare

 [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "Getperson/{id}")]

    List<personClass> Getperson(string id);

回答by alduar

When you are using GET Method the contract must be this.

当您使用 GET 方法时,合同必须是这个。

[WebGet(UriTemplate = "/", BodyStyle = WebMessageBodyStyle.Bare, ResponseFormat = WebMessageFormat.Json)]
List<User> Get();

with this we have a json without the boot parameter

有了这个,我们有一个没有引导参数的json

Aldo Flores @alduar http://alduar.blogspot.com

奥尔多弗洛雷斯@alduar http://alduar.blogspot.com