Search code examples
c#.netwcfsoapwebmethod

How can we specify the return type of a SOAP webservice as JSON format?


This is my method that return xml format but i need to return Json type format.

[WebMethod]
public string GetAllCity(long UID, string IMEINo)
{
    DataSet ds = new DataSet();
    ExeWeb2 cd = new ExeWeb2();

    DataTable dt = new DataTable();
    //booking
    string qyr = "";
    // self booking

    ds = cd.retData("select city_name from city order by city_name");
    dt = ds.Tables[0];
    DataSet ds1 = new DataSet();
    ds1.Tables.Add(dt.Copy());
    ds1.Tables[0].TableName = "City";


    System.IO.MemoryStream s = new System.IO.MemoryStream();
    ds1.WriteXml(s, XmlWriteMode.IgnoreSchema);
    return System.Text.Encoding.UTF8.GetString(s.ToArray());
}

Solution

  • try this:

      DataTable dt11 = ds1.Tables[0];
    
        System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
        List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
    
    
        Dictionary<string, object> row;
        foreach (DataRow dr in dt11.Rows)
        {
            row = new Dictionary<string, object>();
            foreach (DataColumn col in dt11.Columns)
            {
               row.Add(col.ColumnName, dr[col]);
           }
            rows.Add(row);
        }
        return serializer.Serialize(rows);