【问题标题】:how to get json as a result from .net web service如何从.net Web服务中获取json
【发布时间】:2016-05-02 18:47:25
【问题描述】:

我只是想从 .net 网络服务中获取 json
在安卓应用中使用

我的网络方法是……

        [WebService(Namespace = "http://tempuri.org/")]
        [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
        [System.ComponentModel.ToolboxItem(false)]
        // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
        [System.Web.Script.Services.ScriptService]
        public class GetFlash : System.Web.Services.WebService
        {

            [WebMethod]
            [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
            public string GetOneFlash()
            {
                string constring = System.Configuration.ConfigurationManager.ConnectionStrings["eng_lang_tutConnectionString"].ConnectionString;
                SqlConnection con = new SqlConnection(constring);
                con.Open();

                SqlCommand sqlCommand =
                new SqlCommand(@"SELECT * FROM focus WHERE P_ID = " + HttpContext.Current.Request.QueryString["IndexOrder"], con);

                StringBuilder sb = new StringBuilder();
                StringWriter sw = new StringWriter(sb);
                JsonWriter jsonWriter = new JsonTextWriter(sw);

                try
                {
                    SqlDataReader reader = sqlCommand.ExecuteReader();
                    reader.Read();

                    int fieldcount = reader.FieldCount; // count how many columns are in the row
                    object[] values = new object[fieldcount]; // storage for column values
                    reader.GetValues(values); // extract the values in each column

                    jsonWriter.WriteStartObject();
                    for (int index = 0; index < fieldcount; index++)
                    {
                        jsonWriter.WritePropertyName(reader.GetName(index)); // column name
                        jsonWriter.WriteValue(values[index]); // value in column
                    }
                    jsonWriter.WriteEndObject();
                    reader.Close();
                }
                catch (SqlException sqlException)
                {
                    con.Close();
                    return ("No data fetched ..." + "\n" + "---------------------------");
                }
                finally
                {
                    con.Close();
                }
                return sb.ToString();

             }

        }

我的网络服务变得混乱 - 既不是 json 也不是 xml http://englishflash.somee.com/WebService/GetFlash.asmx/GetOneFlash?IndexOrder=1

This XML file does not appear to have any style information associated with it. The document tree is shown below.
<string xmlns="http://tempuri.org/">
{"rownumber":1,"P_ID":120,"F_Eword":"a.m. ","F_Aword":"صباحا ","F_Notes":"","Usage":"","F_pic":null,"F_pronounce":"https://ssl.gstatic.com/dictionary/static/sounds/de/0/a.m..mp3"}
</string>

最大的突破是我得到了这样的 android HTTPrequest 结果

<HTML></HTML> 

我所需要的只是来自 .net 网络服务的 json 像这样
https://api.github.com/user/3bdoelnaggar

【问题讨论】:

标签: c# json web-services


【解决方案1】:

使用以下内容。这适用于所有 HTTP 调用。它从表中获取字符串并按原样返回。 .NET 将其转换为 JSON。请参阅响应格式部分。

    [System.Web.Services.WebMethod]
    [System.Web.Script.Services.ScriptMethod(ResponseFormat = System.Web.Script.Services.ResponseFormat.Json, UseHttpGet = true)]
    public static string GetDetails(int ID)
    {
       PDetails PDetails = new PDetails();
       OrderManager oOrdManager = new OrderManager();
       PDetails = oOrdManager.GetDetailInformation(ID);
       return PDetails.DetailInfo;       
    }

【讨论】:

    【解决方案2】:

    我找到了答案 问题出在

     return sb.ToString();   
    

    我想写

    Context.Response.Write(TheSerializer.Serialize(oBoCityList));
    

    完整代码如下

            [WebMethod]
            [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
            public void GetCities()
            {           
                CityList oBoCityList = new CityList() { new City { Name = "New Delhi", ID = 1 }, new City { Name = "Kanpur", ID = 2 }, new City { Name = "Gurgaon", ID = 3 } };
                JavaScriptSerializer TheSerializer = new JavaScriptSerializer();
                //return TheSerializer.Serialize(oBoCityList);
                Context.Response.Write(TheSerializer.Serialize(oBoCityList));
            }
            }
            public class City
            {
                public City() { }
                public string Name
                { get; set; }
                public Int32 ID
                { get; set; }
            }
            public class CityList : List<City>
            {
                public CityList() { }
            }
    

    【讨论】:

      【解决方案3】:

      以此为例!!

       [WebMethod]
       [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
      public void getCustomers()
      {
          var clientes = from result in dados.clientes select result;
      
          Context.Response.Clear();
          Context.Response.ContentType = "application/json";
          Context.Response.Write(JsonConvert.SerializeObject(clientes));  
      }
      

      现在,当您创建 Web 方法后,使用此 ajax 调用从 Web 服务获取数据

      var url = "YourURL_of_Webservice"; // example :  "http://localhost:54028/webservice.asmx/getCustomers"
      
      $.ajax({
       type: "POST",
       url: url,
       success: function (data) {
        // YOUR CODE FOR SUCCESS BODY
          console.log(data)
       },
       error: function (xmlHttpRequest, textStatus, errorThrown) {
            console.log(xmlHttpRequest.responseText);
            console.log(textStatus);
            console.log(errorThrown);
         }
       });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-09-24
        • 1970-01-01
        • 2016-05-14
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多