convert from SqlDataReader to JSON

后端 未结 13 1200
忘掉有多难
忘掉有多难 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 16:58

    If you want something that'll convert to arbitrary JSON, you could convert by serializing it into a Dictionary(Of string, object) thusly:

    public IEnumerable> Serialize(SqlDataReader reader)
    {
        var results = new List>();
        var cols = new List();
        for (var i = 0; i < reader.FieldCount; i++) 
            cols.Add(reader.GetName(i));
    
        while (reader.Read()) 
            results.Add(SerializeRow(cols, reader));
    
        return results;
    }
    private Dictionary SerializeRow(IEnumerable cols, 
                                                    SqlDataReader reader) {
        var result = new Dictionary();
        foreach (var col in cols) 
            result.Add(col, reader[col]);
        return result;
    }
    

    And then use the NewtonSoft.Json JsonConvert object to get your JSON:

    var r = Serialize(reader);
    string json = JsonConvert.SerializeObject(r, Formatting.Indented);
    

    UPDATE: If you just want to use built-in methods, and you happen to be using MVC, you can use the built in Json helper method on your newly serialized :

    JsonResult Index(int id) {
        var r = Serialize(reader);
        return Json(r, JsonRequestBehavior.AllowGet);
    }
    

提交回复
热议问题