2017-09-28 4 views
0

json形式のデータを返すために.NET Framework 4.0でWebサービスを作成しようとしています。以下はjsonオブジェクトでデータを文字列として返すwebservice

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で始まる返され、元のコンテンツを文字列として保存されているのはなぜ。

答えて

2

はこれを試してみてください:

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

私はクラスから出力を返す従来の方法により、上記の問題を解決しました。

私はdbから返されたデータのクラスを定義しました。クラスのデータを保存し、最終的にクラスをオブジェクトとして返しました。

このようにして、適切なJSON形式で応答を取得することができました。

関連する問題