create JSON string from SqlDataReader

前端 未结 4 1960
予麋鹿
予麋鹿 2021-02-08 03:55

UPDATE

I figured it out. Check out my answer below.


I\'m trying to create a JSON string representing a row from a database table to return in an HTTP res

4条回答
  •  滥情空心
    2021-02-08 04:43

    Got it! Here's the C#...

    // ... SQL connection and command set up, only querying 1 row from the table
    StringBuilder sb = new StringBuilder();
    StringWriter sw = new StringWriter(sb);
    JsonWriter jsonWriter = new JsonTextWriter(sw);
    
    try {
    
        theSqlConnection.Open(); // open the connection
    
        // read the row from the table
        SqlDataReader reader = sqlCommand.ExecuteReader();
        reader.Read();
    
        int fieldcount = reader.FieldCount; // count how many columns are in the row
        object[] values = new object[fieldcount]; // storage for column values
        reader.GetValues(values); // extract the values in each column
    
        jsonWriter.WriteStartObject();
        for (int index = 0; index < fieldcount; index++) { // iterate through all columns
    
            jsonWriter.WritePropertyName(reader.GetName(index)); // column name
            jsonWriter.WriteValue(values[index]); // value in column
    
        }
        jsonWriter.WriteEndObject();
    
        reader.Close();
    
    } catch (SqlException sqlException) { // exception
        context.Response.ContentType = "text/plain";
        context.Response.Write("Connection Exception: ");
        context.Response.Write(sqlException.ToString() + "\n");
    } finally {
        theSqlConnection.Close(); // close the connection
    }
    // END of method
    // the above method returns sb and another uses it to return as HTTP Response...
    StringBuilder theTicket = getInfo(context, ticketID);
    context.Response.ContentType = "application/json";
    context.Response.Write(theTicket);
    

    ... so the StringBuilder sb variable is the JSON object that represents the row I wanted to query. Here is the JavaScript...

    $.ajax({
        type: 'GET',
        url: 'Preview.ashx',
        data: 'ticketID=' + ticketID,
        dataType: "json",
        success: function (data) {
    
            // data is the JSON object the server spits out
            // do stuff with the data
        }
    });
    

    Thanks to Scott for his answer which inspired me to come to my solution.

    Hristo

提交回复
热议问题