【问题标题】:WCF web service returning json format dataWCF Web 服务返回 json 格式数据
【发布时间】:2018-04-22 05:33:43
【问题描述】:

我创建了一个返回 json 格式数据的 WCF 网络服务。我的代码如下:

String sJSONdata = "";

StreamReader reader = new StreamReader(data);
sJSONdata = reader.ReadToEnd();

//'now convert the JSON into a data table
DataTable dt = GetJSONTable(sJSONdata);
dt.TableName = "Customer";

Dictionary<string, string> dict = new Dictionary<string, string>();
foreach (DataRow rs in dt.Rows)
{
    dict = new Dictionary<string, string>();
    foreach (DataColumn col in dt.Columns)
    {
        dict.Add(col.ColumnName, rs[col].ToString());
    }
}
return (new JavaScriptSerializer().Serialize(dict));

我得到以下输出:

{ "SampleServiceResult": "{\"Id\":\"1\",\"姓名\":\"xyz\",\"email\":\"xya@test.com\"}" }

但我希望输出如下:

{ "SampleServiceResult": {"Id":"1","Name":"xyz","email":"xya@test.com"} }

在输出中添加“\”转义字符。如何删除它并返回有效的 json?

我尝试替换“\”,但它不起作用。

谢谢

【问题讨论】:

  • 您为什么要使用桌子?数据看起来更适合作为一个适当的类来序列化/反序列化到/从......你在哪里看输出?如果在调试器中,那么您将看到引号为 \",因为字符串中有双引号。此输出实际上是您在客户端中看到的吗?
  • 仔细检查后,您的结果字典有一个条目,其键为"SampleServiceResult",值为"{\"Id\":\"1\",\"Name\":\"xyz\",\"email\":\"xya@test.com\"}"(这是一个单个字符串)。这表明您的实际问题是 GetJSONTable() 方法返回单个列,而您似乎期望不止一个?正如我上面所说,序列化成与数据匹配的类,而不是尝试使用数据表,除非数据变化很大。
  • @GPW,是的,我在客户端得到了同样的结果。我已经检查了邮递员和 ios 设备中的输出。
  • 查看链接 - 基本上你不应该从 Web 服务返回 JSON(而是创建一个 RESTful 服务),但你也应该返回一个 OBJECT (不要试图自己把它变成一个字符串,让该服务为您进行序列化)。最后,不要乱用字典。如果您知道数据是什么样子,请定义一个看起来相同的类并改用 THAT - 这样您就不需要搞乱字典和数据表了。

标签: c# json wcf


【解决方案1】:

通过在我的代码中应用以下更改,我得到了预期的结果:

  1. 将返回类型从 String 更改为 Stream
  2. 替换了下面的代码

    return (new JavaScriptSerializer().Serialize(dict));

    WebOperationContext.Current.OutgoingResponse.ContentType = "application/json; charset=utf-8"; return new MemoryStream(Encoding.UTF8.GetBytes(sData));

感谢大家的帮助和支持。可能会帮助某人。

【讨论】:

    【解决方案2】:

    最好让 WCF 负责序列化,而不是自己做。

    您可以使用WebGet attribute 并为您的操作合同指定响应格式。

    此外,正如 cmets 中所指出的,您可以返回自己的 .NET 类而不是 Dictionary。

    运营合同可能是这样的:

    [OperationContract]
    [WebGet(UriTemplate = "/GetCustomer", ResponseFormat = WebMessageFormat.Json,
    BodyStyle = WebMessageBodyStyle.Bare)]
    Customer GetCustomer();
    

    使用以下数据合同:

    [DataContract]
    public class Customer
    {
        [DataMember]
        public string Id { get; set; }
        [DataMember]
        public string Name { get; set; }
        [DataMember]
        public string Email { get; set; }
    }
    

    然后你可以用类似这样的代码来实现操作契约:

    public Customer GetCustomer()
    {
            Customer customer = GetCustomerData(); //Get the data and return a customer object
            return customer;
    }
    

    【讨论】:

      猜你喜欢
      • 2012-01-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-19
      • 2017-04-14
      • 1970-01-01
      相关资源
      最近更新 更多