convert from SqlDataReader to JSON

后端 未结 13 1209
忘掉有多难
忘掉有多难 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条回答
  •  萌比男神i
    2020-11-27 17:20

    Another option would be to use James Newton-King's excellent JSON.NET library - http://www.newtonsoft.com/json

    Here's a quick example on how to use it to build up a collection and then output it as a JSON-serialized string:

    using Newtonsoft.Json;
    
    class Program
    {
        static void Main(string[] args)
        {
            ArrayList objs = new ArrayList();
    
            //get the data reader, etc.
            while(o.Read())
            {
                objs.Add(new
                {
                    Id = o["Id"],
                    CN = o["CatName"],
                    Ord = o["Ord"],
                    Icon = o["Icon"]
                });
            }
    
            //clean up datareader
    
            Console.WriteLine(JsonConvert.SerializeObject(objs));
            Console.ReadLine();
        }
    }
    

    You could do the same with your looping by reading in each row of your SqlDataReader into an anonymous object and then use JSON.NET to serialize it to a string.

    Hope this helps!

提交回复
热议问题