Pergunta

I have a Web Service (C#, non-WCF) that should return JSON to mobile app clients, it has an API function like this:

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

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

$.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.

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?

2, If not, are there any (simple) alternative solutions? 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

Foi útil?

Solução

Check this out: stackoverflow.com/a/19564022/487940

Essentially, you want to flush the contents down the Response and set the ContentType of the response:

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;
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top