create JSON string from SqlDataReader

前端 未结 4 1962
予麋鹿
予麋鹿 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:31

    My version:

    This doesn't use DataSchema and also wraps the results in an array, instead of using a writer per row.

    SqlDataReader rdr = cmd.ExecuteReader();
    
    StringBuilder sb = new StringBuilder();
    StringWriter sw = new StringWriter(sb);    
    
    using (JsonWriter jsonWriter = new JsonTextWriter(sw)) 
    {    
        jsonWriter.WriteStartArray();
    
        while (rdr.Read())
        {
            jsonWriter.WriteStartObject();
    
            int fields = rdr.FieldCount;
    
            for (int i = 0; i < fields; i++)
            { 
                jsonWriter.WritePropertyName(rdr.GetName(i));
                jsonWriter.WriteValue(rdr[i]);
            }
    
            jsonWriter.WriteEndObject();
        }
    
        jsonWriter.WriteEndArray();
    }
    

提交回复
热议问题