views:

86

answers:

2

I am storing a multiline textbox value in my db table... When i converted this value to json it gives me an error Error: unterminated string literal...

My sample data was ,

Address Multiline textbox

I am fetching the row to my datatable and then converting it to json,

public string GetJSONString(DataTable table)
    {
        StringBuilder headStrBuilder = new StringBuilder(table.Columns.Count * 5); 
        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);     
        StringBuilder sb = new StringBuilder(table.Rows.Count * 5); 
        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();
    }

The above method doen't seem to handle newline character... Any suggestion...

+2  A: 

JSON strings can't contain a literal newline (ASCII 10). It must be encoded as '\' then 'n'. As Ignacio says, you should be using one of the many JSON libraries.

JSON.NET has built-in support for serializing DataTables, and other types.

Matthew Flaschen
A: 

If you wan't to stay away from third party libraries, you can also use .NET built in serializer

System.Web.Script.Serialization.JavaScriptSerializer

Here is some code, lacking many checks, that turns a DataTable into JSON

 ArrayList list = new ArrayList();
            Dictionary<string, object> jsonOutput = new Dictionary<string, object>();

            foreach (DataRow row in table.Rows)
            {
                foreach (DataColumn col in row.Table.Columns)
                {
                    if (row[col] == DBNull.Value)
                        jsonOutput.Add(col.ColumnName, "");
                    else
                        jsonOutput.Add(col.ColumnName, row[col]);
                }

                list.Add(jsonOutput);
                jsonOutput = new Dictionary<string, object>();
            }


            System.Web.Script.Serialization.JavaScriptSerializer jss = new System.Web.Script.Serialization.JavaScriptSerializer();
            return jss.Serialize(list);
Sir Psycho