我正在尝试在.NET Framework 4.0中创建一个web服务,以json格式返回一些数据。
以下是我的WebMethod代码
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string GetLobMonth(string month)
{
JObject forecastResponse = new JObject();
JObject probabilityResponse = new JObject();
JObject response = new JObject();
string revenue = String.Empty;
String location = String.Empty;
String probability = String.Empty;
SqlConnection dbConnection = new SqlConnection(connection_string);
if (dbConnection.State != System.Data.ConnectionState.Closed)
{
dbConnection.Close();
}
dbConnection.Open();
SqlCommand sqlCommand = new SqlCommand(sqlQuery, dbConnection);
var result = sqlCommand.ExecuteScalar();
if (result != null)
{
using (SqlDataReader reader = sqlCommand.ExecuteReader())
{
while (reader.Read())
{
//revenue = reader[0].ToString();
location = reader[1].ToString();
double figures = double.Parse(reader[0].ToString());
figures = Math.Round(figures, 2);
revenue = figures.ToString();
figures = double.Parse(reader[2].ToString());
figures = Math.Round(figures, 2);
probability = figures.ToString();
forecastResponse.Add(location, revenue);
probabilityResponse.Add(location, probability);
}
}
dbConnection.Close();
response["data1"] = forecastResponse;
response["data2"] = probabilityResponse;
}
else
{
response.Add("error", "No records found");
}
var jsonResponse = JsonConvert.SerializeObject(response.ToString());
return jsonResponse;
}
}
服务以下列格式返回json中的数据:
{"d": "\"{\\r\\n \\\"data1\\\": {\\r\\n \\\"region1\\\": \\\"value1\\\"},\\r\\n \\\"data2\\\": {\\r\\n \\\"region2\\\": \\\"value2\\\",\\r\\n}\\r\\n}\""}
为什么从d开始返回json数据,原始内容以字符串形式存储。
答案 0 :(得分:2)
试试这个:
var jsonResponse = JsonConvert.SerializeObject(response.ToString(), Formatting.Indented);
response.Content = new StringContent(jsonResponse, Encoding.UTF8 , "application/json");
答案 1 :(得分:0)
我通过从类中返回输出的传统方法解决了上述问题。
我为从db中返回的数据定义了一个类。存储了类中的数据,最后将该类作为对象返回。
这样我就能以正确的JSON格式获得响应。