I'm working on an API that will ultimately return a data extract in JSON format. This isn't my exact code. I've simplified the idea so I can convey my question more clearly.
There's a method that queries the database and returns the following columns: CustomerID, CustomerName, Preference, PreferenceValue (where one customer will have dozens of preferences). The dataset is ordered by CustomerID.
My goal is to return a JSON object like this:
{
"Customer": {
"CustomerID": "123",
"CustomerName": "John Smith",
"CustomerPreferences": {
"Color": "Red",
"Texture": "Rough",
"Size": "Medium",
"Weight": "Heavy"
}
}
}
I'm new to C# and OO. So, to these ends, I've been researching and trying various approaches all day. I can do this with a single object no problem, but not with a nested class. My intuition tells me what I'm trying to do shouldn't be much harder... but it continues to elude me.
I tried this (it didn't work). I made this class (note: it is the same shape as the JSON I'm hoping to get):
public class Customer
{
public string CustomerID { get; set; }
public string CustomerName { get; set; }
public class Preferences
{
public string Preference { get; set; }
public string PreferenceValue { get; set; }
}
}
Then I created the objects (although at this point, I'm already sure I'm on the wrong path, since I'm forced to initialize them separately):
List<Customer> lstCustomer = new List<Customer>();
List<Customer.Preference> lstPref = new List<Customer.Preference>();
Then I tried looping through my query results... (not sure why I'm still sharing this, since I know it doesn't work, and I'm likely embarrassing myself!!):
if (rdr.HasRows)
{
string CurrentCustomer = "";
while (rdr.Read())
{
/*
Since the data is sorted by CustID,
I only add the parent class when it changes.
*/
if (CurrentCustomer != rdr["CustID"].ToString())
{
lstCustomer.Add(new Customer
{
CustomerID = rdr["CustID"].ToString(),
CustomerName = rdr["CustomerName"].ToString()
});
CurrentCustomer = rdr["CustID"].ToString();
}
lstPref.Add(new Customer.Preference
{
PrefName = rdr["PreferanceName"].ToString(),
PrefValue = rdr["PreferenceValue"].ToString()
});
}
}
I have the feeling this is relatively easy. I've been searching and searching, and cannot find the solution. Once I have an object created and populated, returning it as JSON is a snap. But I can't figure out how to create this simple data structure!