convert json String to datatable?

jai

While converting json string datatable facing an issue with , (comma) value in value field.

actualy my json string is [{"BNo":"345","GNo":"3453","FirstName":"fjai","LastName":"ljai","Address":"BARETI,CEVO, 13/2","Telephone":"051682247","BirthDate":"23-Jan-1981","Email":""}]

In that please look at the address scenario "Address":"BARETI,CEVO, 13/2"

It has the , in the values field. While converting the string to data base i got error. Here the code which i used convert json string to datatable

public DataTable JsonStringToDataTbl(string jsonString)
{
    DataTable dt = new DataTable();
    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)
        {
            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;
}

The code must omit the , in the value field.. what can i do

keenthinker

If your keys are unknown at the time of being read, then you can use the JObject and the JProperty classes from JSON.Net to retrieve the keys and their values like this:

private void printKeysAndValues(string json)
{
    var jobject = (JObject)((JArray)JsonConvert.DeserializeObject(json))[0];
    foreach (var jproperty in jobject.Properties())
    {
        Console.WriteLine("{0} - {1}", jproperty.Name, jproperty.Value);
    }
}

Applied to two different JSON input string, retrieves the key/value pair:

var json1 = @"[{""BNo"":""345"",""GNo"":""3453"",""FirstName"":""fjai"",""LastName"":""ljai"",""Address"":""BARETI,CEVO, 13/2"",""Telephone"":""051682247"",""BirthDate"":""23-Jan-1981"",""Email"":""""}]";
var json2 = @"[{""Test"": ""A"", ""Text"":""some text"", ""Numbers"":""123""}]";
printKeysAndValues(json1);
Console.WriteLine("-------------------");
printKeysAndValues(json2);

And the output is:

BNo - 345
GNo - 3453
FirstName - fjai
LastName - ljai
Address - BARETI,CEVO, 13/2
Telephone - 051682247
BirthDate - 23-Jan-1981
Email - 
-------------------
Test - A
Text - some text
Numbers - 123

One possibility would be to use the dynamic keyword. You can directly access the field like this:

var json = @"[{""BNo"":""345"",""GNo"":""3453"",""FirstName"":""fjai"",""LastName"":""ljai"",""Address"":""BARETI,CEVO, 13/2"",""Telephone"":""051682247"",""BirthDate"":""23-Jan-1981"",""Email"":""""}]";
dynamic data = JsonConvert.DeserializeObject(json);
// take the first element of the array
string address = data[0].Address;
Console.WriteLine(address.Replace(",", " "));

The output is:

BARETI CEVO  13/2

Note that String.Replace does not fail, if the symbol that should be replaced is not currently present, so "test".Replace(",", " "); will return test.

Another possibility is to use the in ASP.NET build in JSON converter (serializer/deserializer) - NewtonSoft JSON.Net. You can use it in order to regain the structured data. You need to create a class that represents the JSON structure:

public class Data
{
    public string BNo { get; set; }
    public string GNo { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Address { get; set; }
    public string Telephones { get; set; }
    public string BirthDates { get; set; }
    public string Emails { get; set; }
}

Then the current JSON can be converted to an object of type Data using the JsonConvert.DeserializeObject method:

var json = @"[{""BNo"":""345"",""GNo"":""3453"",""FirstName"":""fjai"",""LastName"":""ljai"",""Address"":""BARETI,CEVO, 13/2"",""Telephone"":""051682247"",""BirthDate"":""23-Jan-1981"",""Email"":""""}]";
// remove square braces [ and ] at the start resp. end
var data = JsonConvert.DeserializeObject<Data>(json.Substring(1).Substring(0, json.Length - 2));

Now you can access the Address field and for example replace the , symbol:

Console.WriteLine(data.Address.Replace(",", " "));

The output is:

BARETI CEVO  13/2

I think your service returns also the wrong JSON format. JSON always starts with an object (when not in JavaScript), meaning that everything at the top level must be enclosed within curly braces { and }. If the service should return an array, then it should look like this {"results": [{"BNo":"...},{...}]}. If you can't change the service, then you can adapt / correct the returned string. Add a typed model for the array:

public class DataHolder
{
    public Data[] data { get; set; }
}

and then create a correct JSON object holding an array:

var data = JsonConvert.DeserializeObject<DataHolder>("{\"data\":" + json + "}");
Console.WriteLine(data.data[0].Address.Replace(",", " "));

The output is again the same.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related