//helper to reduce duplicate code and make sure month is in MM format. private void Append_Grouped_Transaction(ref List <Grouped_Transaction> list, int month, int year, double total_credit, double total_debit) { Grouped_Transaction gt = new Grouped_Transaction(); //ensure month is always MM string str_month = month.ToString(); str_month = str_month.PadLeft(2, '0'); gt.year_month = year.ToString() + "-" + str_month.ToString(); gt.monthly_credit = total_credit; gt.monthly_debit = Math.Abs(total_debit); list.Add(gt); }
//this method formats the output Json string based on the transactions grouped by month/year. public void Get_Grouped_Transactions_Json(List <Grouped_Transaction> grouped_transactions, out string grouped_json) { StringBuilder sb = new StringBuilder(); //Bail out early. If list is empty return empty string. if (grouped_transactions.Count == 0) { grouped_json = ""; return; } //build the output JSON based upon the requirements. //the format for each line similar to --> "2014-10": {"spent": "$200.00", "income": "$500.00"}, //the JSON serializer/deserializer library that I am using does not have functionality to //customize the fields to the level that is required so I wrote this. sb.Append("{"); foreach (Grouped_Transaction gt in grouped_transactions) { //format for each line. //"2014-10": {"spent": "$200.00", "income": "$500.00"}, double monthly_credit = Math.Round(gt.monthly_credit, 2); double monthly_debit = Math.Round(gt.monthly_debit, 2); sb.Append("\"" + gt.year_month + "\":" + "{\"spent\":\"$" + monthly_debit.ToString() + "\",\"income\":" + "\"$" + monthly_credit.ToString() + "\"}"); //if it's the very last transaction, append the average month. if (grouped_transactions.IndexOf(gt) == grouped_transactions.Count - 1) { sb.Append(",\n"); //append the averge month. Grouped_Transaction average_month = GetAverageMonth(grouped_transactions); double avg_monthly_credit = Math.Round(average_month.monthly_credit, 2); double avg_monthly_debit = Math.Round(average_month.monthly_debit, 2); sb.Append("\"" + average_month.year_month + "\":" + "{\"spent\":\"$" + avg_monthly_debit.ToString() + "\",\"income\":" + "\"$" + avg_monthly_credit.ToString() + "\"}"); sb.Append("}"); } else { sb.Append(",\n"); } } grouped_json = sb.ToString(); }