1

I have .NET web service which supposed to return the result as JSON, but it returns it as XML? Here is my code.

[WebService(Namespace = "http://tempuri.org/MyService")]
[ScriptService]
public class MyService : System.Web.Services.WebService
{
    [WebMethod, ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public List<MyData> GetMyData(string dataFilter, string param)
    {
        if (dataFilter.ToLower() == "filterValue")
            return getData(param);
        return null;
    } 
}
public class MyData
{
    public string id { get; set; }
    public string name { get; set; }
    protected internal MyData() { } 
}

And here is the web.config

<system.web>
<compilation debug="true" targetFramework="4.0"/>
<httpRuntime/>
<customErrors mode="Off"/>
<webServices>
  <protocols>
    <add name="HttpGet"/>
    <add name="HttpPost"/>
  </protocols>
</webServices>
<pages controlRenderingCompatibilityVersion="3.5" clientIDMode="AutoID"/>

EDIT The web service is working fine only when passing digits in the parameters but it returns internal server error when passing characters inside the parameters. I got confused :O

1 Answer 1

1

Try this code it may help you. Install Newtonsoft.Json package

Code

    public class HelloWorldData
    {
        public String Message;
    }

    [WebMethod]
    public void Select()
    {
        JavaScriptSerializer js = new JavaScriptSerializer();
        Context.Response.Clear();
        Context.Response.ContentType = "application/json";
        HelloWorldData data = new HelloWorldData();
        string sql = "exec YOUR_SP_NAME";
        SqlDataAdapter da = new SqlDataAdapter(sql, System.Configuration.ConfigurationManager.AppSettings["BB_CONSTR"]);
        DataSet ds = new DataSet();
        da.Fill(ds);
        Context.Response.Write(JsonConvert.SerializeObject(ds, Newtonsoft.Json.Formatting.Indented));
    }
Sign up to request clarification or add additional context in comments.

2 Comments

Your code returns JSON format but it does not contain an object to parse it. {[{"Test":"200"}]} but i want it to return {"d":[{"Test":"200"}]}
can u share the screenshot of results.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.