简体   繁体   English

将JSON字符串转换为数据表?

[英]convert json String to datatable?

While converting json string datatable facing an issue with , (comma) value in value field. 在转换json字符串数据表时,值字段中的(,)值存在问题。

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":""}] 实际上我的json字符串是[{"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" "Address":"BARETI,CEVO, 13/2"请查看地址方案"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 这是我使用的代码将json字符串转换为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 代码必须在值字段中省略..我该怎么办

You can convert the JSON value to C# objects using Newtonsoft . 您可以使用Newtonsoft将JSON值转换为C#对象。 This would be easy for you. 这对您来说很容易。 Once you have converted to the below object, you can easily modify the Address property to remove the ',' value. 转换为以下对象后,您可以轻松修改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; }
}

Use the below line to convert to C# object 使用下面的行转换为C#对象

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

Now obj instance holds the C# object which is very easy to manipulate. 现在, obj实例保存了非常易于操作的C#对象。

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: 如果在读取时不知道您的密钥,则可以使用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);
    }
}

Applied to two different JSON input string, retrieves the key/value pair: 应用于两个不同的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);

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. 一种可能性是使用dynamic关键字。 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(",", " "); 请注意,如果当前不存在应替换的符号,则String.Replace不会失败,因此请"test".Replace(",", " "); will return test . 将返回test

Another possibility is to use the in ASP.NET build in JSON converter (serializer/deserializer) - NewtonSoft JSON.Net . 另一种可能性是使用ASP.NET中内置的JSON转换器(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: 您需要创建一个表示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; }
}

Then the current JSON can be converted to an object of type Data using the JsonConvert.DeserializeObject method: 然后,可以使用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));

Now you can access the Address field and for example replace the , symbol: 现在,您可以访问“ Address字段,例如替换,符号:

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

The output is: 输出为:

BARETI CEVO  13/2

I think your service returns also the wrong JSON format. 我认为您的服务还会返回错误的JSON格式。 JSON always starts with an object (when not in JavaScript), meaning that everything at the top level must be enclosed within curly braces { and } . JSON始终以对象开头(如果不是在JavaScript中),这意味着必须将所有顶级内容括在花括号{} 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: 如果服务应该返回一个数组,那么它应该看起来像这样{"results": [{"BNo":"...},{...}]} 。如果您不能更改服务,那么您可以修改/更正返回的字符串,为数组添加类型化的模型:

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

and then create a correct JSON object holding an array: 然后创建一个包含数组的正确JSON对象:

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

The output is again the same. 输出再次相同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM