How to deal with a comma (,) in Json String To DataTable conversion?

Viewed 946

On my asp.net web application I am using a function to convert Json String to Data Table.Function throughs an error while dealing data with a comma(,) in it.
I got the error from : string ColumnsNameString = ColumnsNameData.Substring(0, idx - 1).Replace("\"", "");

enter image description here

This is the C# Function I am using:

public class ConvertJsonStringToDataTable
{
    public DataTable JsonStringToDataTable(string jsonString)
    {
        DataTable dt = new DataTable();
        if (jsonString != "[]" && jsonString != "undefined")
        {
            string[] jsonStringArray = Regex.Split(jsonString.Replace("[", "").Replace("]", ""), "},{");
            List<string> ColumnsName = new List<string>();

            foreach (string jSA in jsonStringArray)
            {
                string[] jsonStringData = Regex.Split(jSA.Replace("{", "").Replace("}", ""), ",");
                foreach (string ColumnsNameData in jsonStringData)
                {
                    if (ColumnsNameData != "")
                    {
                        try
                        {
                            int idx = ColumnsNameData.IndexOf(":");
                            string ColumnsNameString = ColumnsNameData.Substring(0, idx - 1).Replace("\"", "");
                            if (!ColumnsName.Contains(ColumnsNameString))
                            {
                                ColumnsName.Add(ColumnsNameString);
                            }
                        }
                        catch (Exception ex)
                        {
                            throw new Exception(string.Format("Error Parsing Column Name : {0}", ColumnsNameData));
                        }
                    }
                }
                break;
            }

            foreach (string AddColumnName in ColumnsName)
            {
                dt.Columns.Add(AddColumnName);
            }

            foreach (string jSA in jsonStringArray)
            {
                string[] RowData = Regex.Split(jSA.Replace("{", "").Replace("}", ""), ",");
                DataRow nr = dt.NewRow();
                foreach (string rowData in RowData)
                {
                    try
                    {
                        int idx = rowData.IndexOf(":");
                        string RowColumns = rowData.Substring(0, idx - 1).Replace("\"", "");
                        string RowDataString = rowData.Substring(idx + 1).Replace("\"", "");
                        nr[RowColumns] = RowDataString;
                    }
                    catch (Exception ex)
                    {
                        continue;
                    }
                }
                dt.Rows.Add(nr);
            }
            return dt;
        }

        return dt;
    }
}

A portion of Jquery Function

var IdentificationMark = $("[id*=txtIdentificationMark]").val();
var Remarks = $("[id*=txtRemarks]").val();

var dataCustMaster = { IdentificationMark: IdentificationMark, Remarks: Remarks };
var DataCustMaster = (JSON.stringify(dataCustMaster));

if (hasError == false) {
    $.ajax({
    type: "POST",
    url: "CustomerCreation.aspx/InsertDetails",
    data: "{'dataAuthOper':'" + AuthOperData + "','dataAdds':'" + AddsData + "','dataId':'" + IdData + "','dataCustMaster':'" + DataCustMaster + "'}",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: OnSuccess,
    failure: function (response) {
    alert(response.d);
  }

  });
  function OnSuccess(response, userContext, methodName) {
      location.reload(true);
      alert("Saved");
       }
  }

How can I get data with comma(,) ? How can I solve this issue ?? what are the changes I needed to make ??
Help me please,I am a beginner..

1 Answers

It seems that a call to .Substring(0, idx-1) is returning a value less than 0.

You should make sure that idx is greater than or equal to 0.

int idx = ColumnsNameData.IndexOf(":");

if (idx == -1) 
{
    // Do something here. You can throw an exception or return
}

string ColumnsNameString = ColumnsNameData.Substring(0, idx - 1).Replace("\"", "");
if (!ColumnsName.Contains(ColumnsNameString))
{
    ColumnsName.Add(ColumnsNameString);
}

UPDATE

The above code is still relevant for your problem. However, you will need to detect when a comma is located within double quotes. The reason your code is failing is the Split line which creates an array of strings with comma as a splitting point. It finds every single comma and splits the string along those lines.

You cannot rely on a built-in method Split to do this. You'll have to write your own method for parsing the string. If you want to got the easier route, replace the comma separator in your Ajax call and use a different separator like pipe |, hash #, or something else.

Related