gpt4 book ai didi

c# - 如何防止 WebMethod 序列化 json 响应

转载 作者:太空宇宙 更新时间:2023-11-03 23:03:36 24 4
gpt4 key购买 nike

我有一个返回数据的网络方法。我有用于将我的对象序列化为 json 以忽略空值和其他目的的特定代码。

发生的事情是 .Net 再次序列化响应:

对象 = {a:2}

首次序列化 = {"a": "2"}

第二次序列化 = "{\"a\":\"2\"}"

如何防止 .Net 第二次序列化我的响应。

代码:

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static object XXX()
{
return new { a = 2 }.ToJson();
}

最佳答案

.ToJson() 调用是不必要的 - 删除它:

[WebMethod]
public static object XXX()
{
return new { a = 2 };
}

原因是 Web API serializes to JSON by default :

What Gets Serialized?

By default, all public properties and fields are included in the serialized JSON. To omit a property or field, decorate it with the JsonIgnore attribute.

因此,除非明确忽略,或者客户端调用特定的媒体格式化程序(通过 Content-Type 请求 header ),否则您的返回类型将序列化为 JSON。双重序列化是由于额外的 .ToJson() 调用而发生的。

您的 ScriptMethod 属性也是不必要的,因为 JSON 是 ScriptMethodAttribute.ResponseFormat property 的默认值.

关于c# - 如何防止 WebMethod 序列化 json 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42131384/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com