questions/42177475/issue-converting-json-string-to-datatable-c-sharp

CSharp · Console

/Program.cs

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Collections.ObjectModel;
using System.Reflection;
using System.Runtime.Serialization;
using System.Data;
using System.Xml;

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;

namespace Question42177475
{
    // https://stackoverflow.com/questions/42177475/issue-converting-json-string-to-datatable-c-sharp
    public class Result
    {
        public int ID { get; set; }
        public string Reference { get; set; }
        public int Asset { get; set; }
        public int Event { get; set; }
        public string DateEventStart { get; set; }
        public string DateEvent { get; set; }
    }

    public class RootObject<T>
    {
        public int Code { get; set; }
        public T Result { get; set; }
    }

    internal class TestClass
    {
        static string GetJson()
        {
            var json = @"{
  ""Code"": 0,
  ""Result"": [
    {
      ""ID"": 1,
      ""Reference"": ""101"",
      ""Asset"": 200,
      ""Event"": 1,
      ""DateEventStart"": ""2/10/2017 9:08:33 PM"",
      ""DateEvent"": ""2/11/2017 1:00:14 AM""
    }
]
}";
            return json;
        }

        internal static void Test()
        {
            var responsetext = GetJson();

            var rootOfList = JsonConvert.DeserializeObject<RootObject<List<Result>>>(responsetext);
            var rootOfTable = JsonConvert.DeserializeObject<RootObject<DataTable>>(responsetext);
            DataTable table = rootOfTable.Result;

            Console.WriteLine(string.Format("Result of deserializing and reserializing as a {0}:", rootOfList.GetType()));
            Console.WriteLine(JsonConvert.SerializeObject(rootOfList, Newtonsoft.Json.Formatting.Indented));

            Console.WriteLine(string.Format("Result of deserializing and reserializing as a {0}:", rootOfTable.GetType()));
            Console.WriteLine(JsonConvert.SerializeObject(rootOfTable, Newtonsoft.Json.Formatting.Indented));
        }
    }
}

public class Program
{
	public static void Main()
	{
		Console.WriteLine("Json.NET version: " + typeof(JsonSerializer).Assembly.FullName);
		Console.WriteLine("");
		
		Question42177475.TestClass.Test();
	}
}
;