【求助】C#写的WebService,连接数据库后如何返回JSON字符串??

8_M_24 2015-07-08 03:31:16
我现在的问题是,数据库能用WebService连接成功,而且能返回数据。但是,我想返回JSON形式的数据,我现在得到的返回形式是XML。
如下图所示:

以上图片是我现在得到的返回形式。


以上图片是我期望得到的返回形式。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Data;
using System.Data.SqlClient;

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消注释以下行。
[System.Web.Script.Services.ScriptService]

public class Service : System.Web.Services.WebService
{
static String strCon = "Data Source=WZY-PC;Initial Catalog=DB_Haier;Integrated Security=True";
public Service () {

//如果使用设计的组件,请取消注释以下行
//InitializeComponent();
}

[WebMethod(Description = "返回数据测试")]
public DataSet TestReturn()
{
SqlConnection con = new SqlConnection();
SqlCommand cmd = con.CreateCommand();
cmd.CommandText = "select * from TB_Admin";
SqlDataAdapter da = new SqlDataAdapter(cmd.CommandText,strCon);
DataSet ds = new DataSet();
da.Fill(ds);
return ds;
}

}

以上是我的代码。

求教大神我如何修改代码。如果有详细的教程,也可以发给我。网上有好多没用的教程。
...全文
2324 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
L708L 2019-03-13
  • 打赏
  • 举报
回复
解决如下: webservice 返回字符串之前加上下面两句: Context.Response.Write("要返回的字符串"); Context.Response.End(); 如遇中文乱码问题需要在Web.config 配置文件中 <system.web> 节点下加入: <globalization responseEncoding="gb2312" requestEncoding="gb2312" culture="zh-CN"/>
AnyJie 2018-06-05
  • 打赏
  • 举报
回复
解决了也不说下解决方案?
haqihaqi 2017-09-19
  • 打赏
  • 举报
回复
版主最后是如何解决的?我也是纠结了很久都想不出来,刚刚接触,求分享
蒙奇D_ 2016-03-07
  • 打赏
  • 举报
回复
楼主如何解决的?求分享,我现在和你是一样的问题,小女子感激不尽
8_M_24 2015-07-10
  • 打赏
  • 举报
回复
引用 1 楼 aperyx 的回复:
搜索JsonAndDateTable,百度文庫中有代碼,稍改一下,就可以用了 WebMethod public DataSet TestReturn()-->返回類型改為string return JsonAndDateTable.DateTableToJson(ds.Table[0]); 或 Context.Response.Write(JsonAndDateTable.DateTableToJson(ds.Table[0])); Context.Response.Flush();
我已经自己解决了,谢谢,分全都给你啦!
aperyx 2015-07-09
  • 打赏
  • 举报
回复
搜索JsonAndDateTable,百度文庫中有代碼,稍改一下,就可以用了 WebMethod public DataSet TestReturn()-->返回類型改為string return JsonAndDateTable.DateTableToJson(ds.Table[0]); 或 Context.Response.Write(JsonAndDateTable.DateTableToJson(ds.Table[0])); Context.Response.Flush();

12,162

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 Web Services
社区管理员
  • Web Services社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧