wcf接口,外连接查询返回json(vs2017)
关于wcf接口返回json,网上有很多不同的写法,本人主要是将外连接查询到的数据放在datatable中,然后将datatable转换为json格式。
1.首先,先写一个外连接查询(用户名([Users].UserName)到表[Users]的进行比对,验证通过后,外连接查询 表[UserDevices]中对应的[UserDevices].DeviceNum),将查询到的DeviceNum以json格式返回。)
public string SelectLogin(string strName)
{
try
{
strCon.Open();
string strSql = "SELECT [UserDevices].DeviceNum FROM [UserDevices] JOIN [Users] " +
"ON([Users].UserId = [UserDevices].UserId) WHERE [Users].UserName='" + strName + "'";
SqlDataAdapter s = new SqlDataAdapter(strSql, strCon);
DataTable ds = new DataTable();
s.Fill(ds);
string dj = DataTableToJsonWithJsonNet(ds);
return dj;
}
catch (Exception e)
{
throw e;
}
finally
{
strCon.Close();
}
}
2.将datatable转换为json格式(使用Json.Net DLL (Newtonsoft)。注意在svc文件的开头加上
using Newtonsoft.Json;)
public string DataTableToJsonWithJsonNet(DataTable ds)
{
string jsonString = string.Empty;
jsonString = JsonConvert.SerializeObject(ds);
return jsonString;
}
3.引用:在SelectLogin上添加
string dj = DataTableToJsonWithJsonNet(ds);