Reputation: 149
I am trying to create a webservice in .NET Framework 4.0 to return some data in json format.
Below is my code for 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;
}
}
The service return data in json in following format:
{"d": "\"{\\r\\n \\\"data1\\\": {\\r\\n \\\"region1\\\": \\\"value1\\\"},\\r\\n \\\"data2\\\": {\\r\\n \\\"region2\\\": \\\"value2\\\",\\r\\n}\\r\\n}\""}
Why is the json data returned beginning with d and the original content is stored as string.
Upvotes: 0
Views: 1233
Reputation: 149
I solved the above problem by the conventional way of returning the output from a class.
I defined a class for the data returned from db.Stored the data in the class and finally returned the class as an object.
This way I was able to get the response in proper JSON format.
Upvotes: 0
Reputation: 71
Try this:
var jsonResponse = JsonConvert.SerializeObject(response.ToString(), Formatting.Indented);
response.Content = new StringContent(jsonResponse, Encoding.UTF8 , "application/json");
Upvotes: 2