convert from SqlDataReader to JSON

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

    I encounter use cases where the number of rows being returned by the data reader may become problematic with respect to memory consumption. The following code uses a JsonWriter (from JSON.NET) over a stream. One can certainly debate the utility of enormous JSON documents, but sometimes our use cases are dictated by others :-)

    A few notes:

    • My SqlDataReader may contain multiple result sets ('tables')
    • I may be sending the output to a FileStream or an HttpResponse stream
    • I've 'abstracted' my object names to match the first column returned per result set
    • Because of the potential for large result sets, I use async methods of the SqlDataReader.
    • I'm letting JSON.NET handle all the serialization issue of the actual data contained in the data reader results.

    The code:

    var stream = ... // In my case, a FileStream or HttpResponse stream
    using (var writer = new JsonTextWriter(new StreamWriter(stream)))
    {
        writer.WriteStartObject();  
        do
        {
            int row = 0;
            string firstColumn = null;
            while (await reader.ReadAsync())
            {
                if (row++ == 0)
                {
                    firstColumn = reader.GetName(0);
                    writer.WritePropertyName(string.Format("{0}Collection", firstColumn));
                    writer.WriteStartArray();   
                }
                writer.WriteStartObject();
                for (int i = 0; i < reader.FieldCount; i++)
                {
                    if (!reader.IsDBNull(i)) { 
                        writer.WritePropertyName(reader.GetName(i));
                        writer.WriteValue(reader.GetValue(i));
                    }
                }
                writer.WriteEndObject(); 
            }
            writer.WriteEndArray();
        } while (await reader.NextResultAsync());
    
        writer.WriteEndObject();
    }
    

    An example of heterogeneous output would be:

    {
        "ContactCollection": {
            "ContactItem": [{
                    "ContactID": "1",
                    "Contact": "Testing",
                },
                {
                    "ContactID": "2",
                    "Contact": "Smith, John",
                },
                {
                    "ContactID": "4",
                    "Contact": "Smith, Jane",
                }
            ],
            "MessageItem": [{
                    "MessageID": "56563",
                    "Message": "Contract Review Changed",
                },
                {
                    "MessageID": "56564",
                    "Message": " Changed",
                },
                {
                    "MessageID": "56565",
                    "Message": "Contract Review - Estimated Completion Added.",
                }
            ]
        }
    }
    

    Reference:

    • http://www.newtonsoft.com/json/help/html/Performance.htm
    0 讨论(0)
提交回复
热议问题