【问题标题】:webservice returning data as string in json objectWeb服务将数据作为json对象中的字符串返回
【发布时间】:2017-09-28 12:15:20
【问题描述】:

我正在尝试在 .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}\""}

为什么返回的json数据以d开头,而原始内容存储为字符串。

【问题讨论】:

    标签: c# .net json web-services


    【解决方案1】:

    试试这个:

    var jsonResponse = JsonConvert.SerializeObject(response.ToString(), Formatting.Indented);
    response.Content = new StringContent(jsonResponse, Encoding.UTF8 , "application/json");
    

    【讨论】:

      【解决方案2】:

      我通过从类返回输出的常规方式解决了上述问题。

      我为db返回的数据定义了一个类。将数据存储在类中,最后将该类作为对象返回。

      通过这种方式,我能够以正确的 JSON 格式获得响应。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-10-24
        • 1970-01-01
        • 1970-01-01
        • 2017-06-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多