convert from SqlDataReader to JSON

后端 未结 13 1236
忘掉有多难
忘掉有多难 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:07

    Further to Jonathan's Answer, I had a similar requirement in ASP.NET Core to convert the result of an SQLDataReader to a JSON string or a Result Object, so I created an extension method for it as :

     public static class MyExtensions
        {
            public async static Task toJSON(this SqlDataReader reader)
            {            
                var results = await reader.GetSerialized();
                return JsonConvert.SerializeObject(results, Formatting.Indented);
            }
            public async static Task>> GetSerialized(this SqlDataReader reader)
            {
                var results = new List>();
                var cols = new List();
                for (var i = 0; i < reader.FieldCount; i++)
                    cols.Add(reader.GetName(i));
    
                while (await reader.ReadAsync())
                    results.Add(SerializeRow(cols, reader));
    
                return results;
            }
            private static Dictionary SerializeRow(IEnumerable cols,
                                                            SqlDataReader reader)
            {
                var result = new Dictionary();
                foreach (var col in cols)
                    result.Add(col, reader[col]);
                return result;
            }
        }
    

    & used it as per my requirement as :

    var result = await reader.GetSerialized(); //to get the result object
    

    or

    string strResult = await reader.toJSON(); //to get the result string
    

    I created an async method because I had some other things to be done till the reading was finished from database.

提交回复
热议问题