create JSON string from SqlDataReader

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

    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;
        }
    

提交回复
热议问题