vpetkovic
3/26/2019 - 5:34 PM

[CLASS] JSONParser

This is a parser class for JSON string

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace JSONParser
{
    class agentListParser : IDisposable
    {
        private static DataTable dt;

        public static DataTable BuildTableFromJSON(string json)
        {
            // We now want to filter users by security profile (profileId) to precisly 
            // get only CSR agents. We have to serialize JSON for further parsing
            JObject allUsers = JObject.Parse(json);
            var agents = //JsonConvert.SerializeObject(
                            from p in allUsers["agents"]
                            where p.Value<long>("profileId") == 8 && p.Value<string>("userName").Contains("nyscspc.com")
                            select new
                            {
                                agentId = p["agentId"],
                                userName = p["userName"],
                                internalId = p["internalId"],
                                firstName = p["firstName"],
                                lastName = p["lastName"],
                                profileId = p["profileId"],
                                isActive = p["isActive"]
                            }; //Formatting.Indented);

            // Creating table for JSON
            dt = new DataTable { TableName = "vcc_Agents" };
            dt.Clear();
            dt.Columns.Clear();

            dt.Columns.Add("agentId", typeof(int));
            dt.Columns.Add("userName", typeof(string));
            dt.Columns.Add("internalId", typeof(string));
            dt.Columns.Add("firstName", typeof(string));
            dt.Columns.Add("lastName", typeof(string));
            dt.Columns.Add("profileId", typeof(int));
            dt.Columns.Add("isActive", typeof(bool));

            // Inserting JSON to datatable
            foreach(var csr in agents)
            {
                dt.Rows.Add(new object[]{
                    csr.agentId,
                    csr.userName,
                    csr.internalId,
                    csr.firstName,
                    csr.lastName,
                    csr.profileId,
                    Convert.ToBoolean(csr.isActive)
                });
            }

            return dt;
        }

        #region IDisposable Support
        private bool disposedValue = false;
        protected virtual void Dispose(bool disposing)
        {
            if (!disposedValue)
            {
                if (disposing)
                {
                    if (dt != null) dt.Dispose();
                }
                disposedValue = true;
            }
        }
        public void Dispose()
        {
            Dispose(true);
        }
        #endregion
    }
}