Request Processing Logic
To handle incoming web requests efficiently, we can implement a generic handler that enspects specific parameters to determine the appropriate action. The following example demonstrates how to route requests based on an operation parameter. Depending on the value received, the handler either fetches a specific list of materials or retrieves a comprehensive dataset from the database.
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "application/json";
string operation = context.Request["operation"];
switch (operation)
{
case "fetch_materials":
GetMaterialList();
break;
default:
GetAllInventoryRecords();
break;
}
}
Database Extraction and Serialization
This method illustrates retrieving data from a SQL Server database and converting it into a JSON format suitable for client-side consumption. We utilize ADO.NET components such as SqlConnection, SqlDataAdapter, and DataSet to manage the data retrieval. Finally, JsonConvert.SerializeObject is used to transform the DataTable into a JSON string.
private string GetAllInventoryRecords()
{
const string queryCommand = "SELECT * FROM Inventory_Table";
string connectionString = "server=192.168.1.1;database=ProductionDB;uid=appUser;pwd=securePassword";
using (var dbConnection = new SqlConnection(connectionString))
{
dbConnection.Open();
var sqlCommand = new SqlCommand(queryCommand, dbConnection);
// Initialize the adapter to bridge the database and the dataset
var dataAdapter = new SqlDataAdapter();
dataAdapter.SelectCommand = sqlCommand;
// Create a dataset to hold the retrieved data
var dataSet = new DataSet();
dataAdapter.Fill(dataSet, "inventoryData");
// Retrieve the specific table and serialize it to JSON
DataTable resultTable = dataSet.Tables[0];
string jsonOutput = JsonConvert.SerializeObject(resultTable);
return jsonOutput;
}
}
JSON String Manipulation and Deserialization
When dealing with JSON strings that contain escape characters (such as backslashes), it is often necessary to clean the string before parsing. Below are several approaches to handle these scenarios, ranging from simple string replacement to object deserialization.
Cleaning Escaped Characters
If a JSON string is escaped (e.g., "{\"id\":1}"), the backslashes must be removed to parse it correctly.
string rawJson = "{\"No\":\"1\",\"ID\":\"1\",\"TIMESTAMP\":\"2023/10/16 09:18\",\"USER\":\"John Doe\"}";
// Method 1: Using String.Replace to remove escape backslashes
string cleanJson = rawJson.Replace(@"\", "");
Parsing JSON into Objects
To work with the data strongly, you can deserialize the JSON string into a defined C# class. The JsonConvert.DeserializeObject<T> method maps the JSON properties to the class fields.
// Define a data model matching the JSON structure
public class UserLog
{
public string No;
public int ID;
public string TIMESTAMP;
public string USER;
}
// Deserialize the string into the UserLog object
UserLog logEntry = JsonConvert.DeserializeObject<UserLog>(cleanJson);
Console.WriteLine($"Deserialized Timestamp: {logEntry.TIMESTAMP}");