如何使用json.net将数据表转换为json?有什么建议…我已经下载了必要的二进制文件…我应该使用哪个类将数据表转换为json?到目前为止,使用此方法通过传递数据表来获取json字符串…
public string GetJSONString(DataTable table) { StringBuilder headStrBuilder = new StringBuilder(table.Columns.Count * 5); //pre-allocate some space, default is 16 bytes for (int i = 0; i < table.Columns.Count; i++) { headStrBuilder.AppendFormat("\"{0}\" : \"{0}{1}¾\",", table.Columns[i].Caption, i); } headStrBuilder.Remove(headStrBuilder.Length - 1, 1); // trim away last , StringBuilder sb = new StringBuilder(table.Rows.Count * 5); //pre-allocate some space sb.Append("{\""); sb.Append(table.TableName); sb.Append("\" : ["); for (int i = 0; i < table.Rows.Count; i++) { string tempStr = headStrBuilder.ToString(); sb.Append("{"); for (int j = 0; j < table.Columns.Count; j++) { table.Rows[i][j] = table.Rows[i][j].ToString().Replace("'", ""); tempStr = tempStr.Replace(table.Columns[j] + j.ToString() + "¾", table.Rows[i][j].ToString()); } sb.Append(tempStr + "},"); } sb.Remove(sb.Length - 1, 1); // trim last , sb.Append("]}"); return sb.ToString(); }
现在我想使用json.net,但不知道从哪里开始。
string json = JsonConvert.SerializeObject(table, Formatting.Indented);
编辑:当然,您不需要缩进格式,但是它使它美观且可读。