将json String转换为datatable?

时间:2015-08-22 09:24:57

标签: c# asp.net json

转换json字符串数据表时,在值字段中使用(逗号)值来解决问题。

我的json字符串是[{"BNo":"345","GNo":"3453","FirstName":"fjai","LastName":"ljai","Address":"BARETI,CEVO, 13/2","Telephone":"051682247","BirthDate":"23-Jan-1981","Email":""}]

请查看地址方案"Address":"BARETI,CEVO, 13/2"

在值字段中有。在将字符串转换为数据库时,我收到了错误。这里使用的代码将json字符串转换为数据表

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;
}

代码必须省略值字段中的..我能做什么

2 个答案:

答案 0 :(得分:0)

您可以使用Newtonsoft将JSON值转换为C#对象。这对你来说很容易。转换为以下对象后,您可以轻松修改Address属性以删除','值。

public class RootObject
{
  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 Telephone { get; set; }
  public string BirthDate { get; set; }
  public string Email { get; set; }
}

使用以下行转换为C#对象

var jsonString = "The output of your webservice";
var obj = Newtonsoft.Json.JsonConvert.DeserializeObject<RootObject>(jsonString);

现在obj实例保存了一个非常容易操作的C#对象。

答案 1 :(得分:0)

如果您的密钥在读取时未知,那么您可以使用JSON.Net中的JObjectJProperty类来检索密钥及其值,如下所示:

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);
    }
}

应用于两个不同的JSON输入字符串,检索键/值对:

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);

输出是:

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

一种可能性是使用dynamic关键字。您可以直接访问该字段:

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(",", " "));

输出结果为:

BARETI CEVO  13/2

请注意String.Replace如果当前不存在应替换的符号,则不会失败,因此"test".Replace(",", " ");将返回test

另一种可能性是在JSON转换器(序列化器/反序列化器)中使用ASP.NET构建 - NewtonSoft JSON.Net。您可以使用它来重新获得结构化数据。您需要创建一个表示JSON结构的类:

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; }
}

然后可以使用JsonConvert.DeserializeObject方法将当前JSON转换为Data类型的对象:

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));

现在,您可以访问Address字段,例如替换,符号:

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

输出结果为:

BARETI CEVO  13/2

我认为您的服务也返回了错误的JSON格式。 JSON始终以对象(不在JavaScript中)开头,这意味着顶级的所有内容都必须包含在大括号{}中。如果服务应该返回一个数组,那么它应该看起来像{"results": [{"BNo":"...},{...}]}。如果您无法更改服务,则可以调整/更正返回的字符串。为数组添加一个类型化的模型:

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

然后创建一个包含数组的正确JSON对象:

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

输出再次相同。