convert from SqlDataReader to JSON

后端 未结 13 1213
忘掉有多难
忘掉有多难 2020-11-27 16:26
public string toJSON(SqlDataReader o)
{
    StringBuilder s = new StringBuilder();
    s.Append(\"[\");
    if (o.HasRows)
        while (o.Read())
            s.App         


        
13条回答
  •  借酒劲吻你
    2020-11-27 17:20

    I made the following method where it converts any DataReader to JSON, but only for single depth serialization:

    you should pass the reader, and the column names as a string array, for example:

    String [] columns = {"CustomerID", "CustomerName", "CustomerDOB"};
    

    then call the method

    public static String json_encode(IDataReader reader, String[] columns)
        {
            int length = columns.Length;
    
            String res = "{";
    
            while (reader.Read())
            {
                res += "{";
    
                for (int i = 0; i < length; i++)
                {
                    res += "\"" + columns[i] + "\":\"" + reader[columns[i]].ToString() + "\"";
    
                    if (i < length - 1)
                        res += ",";
                }
    
                res += "}";
            }
    
            res += "}";
    
            return res;
        }
    

提交回复
热议问题