1

I am using this method to return a XML as result. I need to return a json object after executing the stored procedure. Where should I edit the following code to return a JSON object?

public XmlElement GetGraphData(int eventTypeID, int patientID)
{
    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["dbconnection"].ToString());
    con.Open();

    SqlCommand cmd = new SqlCommand("sp_GetGraphData", con);
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.Parameters.AddWithValue("@EventID", eventTypeID);
    cmd.Parameters.AddWithValue("@PatientID", patientID);

    cmd.ExecuteNonQuery();

    SqlDataAdapter da = new SqlDataAdapter(cmd);

    DataSet ds = new DataSet();
    da.Fill(ds);

    con.Close();

    XmlDataDocument xmldata = new XmlDataDocument(ds);
    XmlElement xmlElement = xmldata.DocumentElement;
}
5
  • you want to convert dataset to json object . right ? Commented Oct 23, 2015 at 5:45
  • 1
    Side note: you should not use the sp_ prefix for your stored procedures. Microsoft has reserved that prefix for its own use (see Naming Stored Procedures), and you do run the risk of a name clash sometime in the future. It's also bad for your stored procedure performance. It's best to just simply avoid sp_ and use something else as a prefix - or no prefix at all! Commented Oct 23, 2015 at 5:45
  • 1
    Also - you're executing the query twice - once on ExecuteNonQuery, and a second time on da.Fill(ds) - don't do that! What are you trying to do? Load data from the database? Don't use ExecuteNonQuery for that! This call is only intended for SQL statements that don't return any data! (Like INSERT, DELETE) Commented Oct 23, 2015 at 5:46
  • yes Amey Deshpande .. You are right Commented Oct 23, 2015 at 5:47
  • you can use Newtonsofts Json.Net Commented Oct 23, 2015 at 5:48

2 Answers 2

4

SQL Server 2016 has FOR JSON clause that formats query result directly in query/stored procedure - see https://msdn.microsoft.com/en-us/library/dn957476.aspx

Sign up to request clarification or add additional context in comments.

Comments

4

For return in JSON format Create SP like

CREATE PROCEDURE spGetAlluser 

AS
BEGIN
    Select * from AspNetUsers FOR JSON AUTO
END
GO

and for get user detail in class obj

var UserDetails=JsonConvert.DeserializeObject<string>(result)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.