【发布时间】:2011-04-05 15:36:24
【问题描述】:
更新
我想通了。 Check out my answer below.
我正在尝试创建一个 JSON 字符串来表示数据库表中的一行以在 HTTP 响应中返回。似乎Json.NET 将是一个很好的工具。但是,我不确定如何构建 JSON 字符串而我正在从数据库中读取。
问题被讨厌的cmets标记/******** ********/
// connect to DB
theSqlConnection.Open(); // open the connection
SqlDataReader reader = sqlCommand.ExecuteReader();
if (reader.HasRows) {
while(reader.Read()) {
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
using (JsonWriter jsonWriter = new JsonTextWriter(sw)) {
// read columns from the current row and build this JsonWriter
jsonWriter.WriteStartObject();
jsonWriter.WritePropertyName("FirstName");
// I need to read the value from the database
/******** I can't just say reader[i] to get the ith column. How would I loop here to get all columns? ********/
jsonWriter.WriteValue(... ? ...);
jsonWriter.WritePropertyName("LastName");
jsonWriter.WriteValue(... ? ...);
jsonWriter.WritePropertyName("Email");
jsonWriter.WriteValue(... ? ...);
// etc...
jsonWriter.WriteEndObject();
}
}
}
问题是我不知道如何从SqlReader 的行中读取每一列,以便我可以调用WriteValue 并为其提供正确的信息并将其附加到正确的列名。所以如果一行看起来像这样......
| FirstName | LastName | Email |
...我将如何为每个这样的行创建一个JsonWriter,以便它包含该行的所有列名和每列中的相应值,然后使用该JsonWriter 来构建一个准备好的 JSON 字符串用于通过 HTTP 响应返回?
如果我需要澄清任何事情,请告诉我。
【问题讨论】:
标签: c# asp.net database json json.net