0

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!

3 Answers 3

3

You're not that far off. I'd go with something like this

public class Customer
    {
        public string CustomerID { get; set; }
        public string CustomerName { get; set; }
        public Dictionary<string, string> Preferences { get; set; }
        public Customer()
        {
            Preferences = new Dictionary<string, string>();
        }

    }

and

List<Customer> customers = new List<Customer>();

            if (rdr.HasRows)
            {
                Customer CurrentCustomer = new Customer();
                while (rdr.Read())
                {
                    /*
                   Since the data is sorted by CustID, 
                   I only add the parent class when it changes.
                   */
                    if (CurrentCustomer.CustomerID != rdr["CustID"].ToString())
                    {
                        CurrentCustomer = new Customer()
                        {
                            CustomerID = rdr["CustID"].ToString(),
                            CustomerName = rdr["CustomerName"].ToString()
                        };
                        customers.Add(CurrentCustomer);
                    }
                    CurrentCustomer.Preferences.Add(rdr["PreferanceName"].ToString(),
                         rdr["PreferenceValue"].ToString());
                }
            }

but try not to butcher the formatting like I did ...

Sign up to request clarification or add additional context in comments.

Comments

1

It seems to me your JSON structure and your class structure don't really match. Instead of a nested class, consider using a dictionary to match a preference name to its value.

public class Customer
{
    public string CustomerID { get; set; }
    public string CustomerName { get; set; }
    public Dictionary<string, string> Preferences { get; }
}

Then you can add preferences to your dictionary using the usual add method.

Comments

0

Move preferences outside of your Customer class, and define a property instead:

public class Customer
{
    public string CustomerID { get; set; }
    public string CustomerName { get; set; }
    public List<Preference> Preferences { get; set;}
}

public class Preference
{
    public string Preference { get; set; }
    public string PreferenceValue { get; set; }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.