locked
How To Split String and Display result on DataTable RRS feed

  • Question

  • User-1766123879 posted

    Good day all, I have this string 

    [{"service":"text","reference":"5dcfc526b883867e194e55202erdda8b2812","status":"DELIVERED"},
    {"service":"text","reference":"7f8924de616129f2ac6ec1c85ddd5438d9","status":"DELIVERED"},
    {"service":"text","reference":"02c17e2ccbf04f6116e3758a129dwrg30c73","status":"DELIVERED"}] // This is my datatable DataTable table = new DataTable(); DataColumn ID = table.Columns.Add("ID", typeof(string)); DataColumn Status = table.Columns.Add("status", typeof(string)); string source = rfs; string[] lines = source.Split(new[] { "\r\n", "\r", "\n"}, StringSplitOptions.None); foreach (var line in lines) { string[] a = line.Split('"'); DataRow row = table.NewRow(); row.SetField(ID, a[7]); row.SetField(Status, a[11]); table.Rows.Add(row); } dy.DataSource = table; dy.DataBind(); I am able to get the first role and display the result on datatable which is this //"service":"text","reference":"5dcfc526b883867e194e55202a8b2812","status":"DELIVERED" I want to display all the records ...But i am able to display only one record.. Where do i get it wrong

    Friday, May 24, 2019 11:39 AM

Answers

  • User765422875 posted

    Your data is in JSON format. You should use JSON.NET and parse it. JSON.NET is available via NuGet.

    First create a class that represents your JSON.

            public class MyClass
            {
                public string service { get; set; }
                public string reference { get; set; }
                public string status { get; set; }
            }

    Then the library will parse it for you.

    var data = JsonConvert.DeserializeObject<List<MyClass>>("YOUR JSON HERE");
    
    foreach (var item in data)
    {
      // add rows to your DataTable
    }

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, May 24, 2019 12:00 PM

All replies

  • User765422875 posted

    Your data is in JSON format. You should use JSON.NET and parse it. JSON.NET is available via NuGet.

    First create a class that represents your JSON.

            public class MyClass
            {
                public string service { get; set; }
                public string reference { get; set; }
                public string status { get; set; }
            }

    Then the library will parse it for you.

    var data = JsonConvert.DeserializeObject<List<MyClass>>("YOUR JSON HERE");
    
    foreach (var item in data)
    {
      // add rows to your DataTable
    }

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, May 24, 2019 12:00 PM
  • User-1766123879 posted

    Thanks a billion.. it works

    Saturday, May 25, 2019 4:43 AM