其他分享
首页 > 其他分享> > 用.net写了一个WebServices接口文件,输出json,记录一下遇到的问题

用.net写了一个WebServices接口文件,输出json,记录一下遇到的问题

作者:互联网

一、把类序列化为json,需要用到JavaScriptSerializer

private string tojson(clsMiInfo info)
        {
            StringBuilder sb = new StringBuilder();
            JavaScriptSerializer json = new JavaScriptSerializer();
            json.Serialize(info, sb);
            return sb.ToString();
        }

二、输出的json头部有<string xmlns="http://tempuri.org/">字样

当然可以直接用replace也能去除,但感觉不太好,

搜索了一下,基本有3种方案:

1、把webservice接口头部的代码部分做如下处理,但是我的并没有生效

[WebService(Namespace = "")]
//[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]

2、把webservice的接口函数返回值设成void,然后函数最后直接用下面代码输出,这个最好用

[WebMethod]
  public void GetJson(String sJson)
  {
    Context.Response.Charset = "UTF-8"; //设置字符集类型
    Context.Response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8");
    Context.Response.Write(sJson);
    Context.Response.End();
  }

3、有一种方法说是直接输出xmldocument对象,具体代码我不会用

标签:输出,json,WebServices,Context,sb,JavaScriptSerializer,net,Response
来源: https://blog.csdn.net/rztyfx/article/details/114214170