简体   繁体   English

浏览器如何显示从C#Web服务返回的JSON

[英]How can browsers display JSON returned from C# Web Service

I have a Web Service (C#, non-WCF) that should return JSON to mobile app clients, it has an API function like this: 我有一个Web服务(C#,非WCF),应将JSON返回到移动应用程序客户端,它具有如下API函数:

[WebMethod]
[ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
public Animal AnimalInformation(int animalID) {
       Animal animal = new Animal();

       animal.name = AnimalNameForID(animalID);
       animal.color = AnimalColorForID(animalID);

       return animal;
}

Although its response format is set to JSON, the response it displays in the browser is still XML, like this: 尽管其响应格式设置为JSON,但它在浏览器中显示的响应仍为XML,如下所示:

<Animal>
<Name>Vicky</Name>
<Color>Grey</Color>
</Animal>

I've been looking around for an answer and found out that this is related to the client's reception format, according to this thread , and the thread suggests to use this piece of javascript code to view the JSON return: 根据该线程 ,我一直在寻找答案,并发现这与客户端的接收格式有关,该线程建议使用这段JavaScript代码查看JSON返回值:

$.ajax({
    type: "POST",
    contentType: "application/json; charset=utf-8;",
    url: "http://MyWebServiceURL",
    data: JSON.stringify({ ParameterName: "DataToSend" }),
    dataType: "json",
    success: function (data, textStatus, jqXHR) {
        //do something
    },
    error: function (jqXHR, textStatus, errorThrown) {
        //fail nicely
    }
});

I wasn't able to get this piece of js code to work, it always fails. 我无法使这段js代码正常工作,但总是失败。

My questions: 我的问题:

1, Is there any settings can be set in my browser so that it asks for JSON instead of XML from the Web Service? 1,我的浏览器中是否可以设置任何设置,以便它从Web服务中请求JSON而不是XML?

2, If not, are there any (simple) alternative solutions? 2,如果没有,是否有(简单)替代解决方案? I'm building this Web Service for my app, but I haven't started working on the app yet, so please don't suggest using app as the test client for WS 我正在为我的应用程序构建此Web服务,但是尚未开始使用该应用程序,因此请不要建议将应用程序用作WS的测试客户端。

Check this out: stackoverflow.com/a/19564022/487940 检查一下: stackoverflow.com/a/19564022/487940

Essentially, you want to flush the contents down the Response and set the ContentType of the response: 本质上,您希望将内容沿Response刷新并设置Response的ContentType:

public class WebService1 : System.Web.Services.WebService
{
    [WebMethod]
    [ScriptMethod(UseHttpGet=true ,ResponseFormat = ResponseFormat.Json)]
    public void HelloWorld()
    {
        JavaScriptSerializer js = new JavaScriptSerializer();
        Context.Response.Clear();
        Context.Response.ContentType = "application/json";           
        HelloWorldData data = new HelloWorldData();
        data.Message = "HelloWorld";
        Context.Response.Write(js.Serialize(data));
    }
}

public class HelloWorldData
{
   public String Message;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM