从 ASMX Web 服务返回 JSON,无需 XML 包装器?
我需要从 C# Web 服务获取 Json 数据。
我知道有几个基于此的问题,相信我,我已经阅读了很多,但只是让我更加困惑。
这就是我所做的:
在我的网络服务中,我已包含: [System.Web.Script.Services.ScriptService]
对于类 & [ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet = true)]
对于该方法,
我还使用了 JavaScriptSerializer()
将我的数据转换为
我调用的 字符串使用 $.getJSON()
的服务
如果我不使用它,则会收到跨域引用错误。
为此,我必须设置 m 服务来获取回调函数名称 所以我传递 this.Context.Request["callback"]
+ 序列化的 Json 数据;
但在输出中,我将其包装在
< string xmlns="http://XYZ...">
标签中的数据采用我需要的格式
我还尝试使用以下命令设置内容类型: $.ajaxSetup({ scriptCharset: "utf-8" , contentType: "application/json ; charset=utf-8"});
但仍然没有成功。
后来添加:我接受了 frenchie 的 anwser,因为我知道这是正确的方法,但我仍然无法让它工作......我只是把 webservice &同一域中的网站使用 xml,我知道这不是最好的方法,但我花了 2 天的时间&不能再浪费了。
I need to get Json data from a C# web service.
I know there are several questions based on this, trust me I have read through quite a few but only to confuse me further.
This is what I have done :
In my web service I have included : [System.Web.Script.Services.ScriptService]
for the class & [ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet = true)]
for the method
I have also used a JavaScriptSerializer()
to convert my data to a string
I am calling this service using $.getJSON()
If I don't use that I get an Cross domain reference error.
To do this I had to setup m service to get the callback function name
so I am passing this.Context.Request["callback"]
+ serialized Json Data;
But in the output I get it wrapped in
< string xmlns="http://XYZ...">
The data within the tags is in the format I need
I also tried setting content type using : $.ajaxSetup({ scriptCharset: "utf-8" , contentType: "application/json; charset=utf-8"});
But still no success.
Addded later: I accepted frenchie's anwser beacuse I know it is the correct approach but I stil cud not get it to work... I just put the webservice & website in the same domain & used xml, I know it wasnt the best way, but I had spent 2 days on it & could not afford to waste more.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用这个:
然后在服务器端,在 AppCode 文件夹中自动生成的代码隐藏文件中,编写如下内容:
如果不使用自定义转换器,则 json 字符串和 c# 类之间的属性服务器端对象的定义必须匹配才能进行反序列化。对于序列化,如果您没有自定义转换器,则 json 字符串将包含 C# 类的每个属性。您可以在 C# 类中的属性定义之前添加
[ScriptIgnore]
,如果您不指定自定义转换器,则该属性将被序列化器忽略。Use this:
and then on the server side, in the code behind file that's auto-generated in your AppCode folder, you write something like this:
If you don't use a custom converter, the properties between the json string and the c# class definition of your server-side object must match for the deserialization to work. For the serialization, if you don't have a custom converter, the json string will include every property of your c# class. You can add
[ScriptIgnore]
just before a property definition in your c# class and that property will be ignored by the serializer if you don't specify a custom converter.