0

I would like to create a JSON file with the following format.

     {
      "Employee1": {
        "Year1": {
          "StartRange": 11,
          "EndRange": 22
        },
      "Year2": {
        "StartRange": 22,
        "EndRange": 45
      }

    },
      "Employee2": {
        "Year1": {
          "StartRange": 11,
          "EndRange": 33
        },
      "Year2": {
        "StartRange": 11,
        "EndRange": 35
      }          
    }
  }

Here os my C# code to get the JSON Format

public void createFile(DataTable dTable)
        {

            string fileName = @"C:\Users\Documents\JSON\JsonConfig" + DateTime.Now.ToString("_dd_MM_yyyy_hh_mm_ss") + ".json";

            List<string> EmployeeList= new List<string>();
            ParentGroupList.Add("Employee1");
            ParentGroupList.Add("Employee2");

            if (!File.Exists(fileName))
            {
                FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write);
                StreamWriter sw = new StreamWriter(fs);

                JsonTextWriter writer = new JsonTextWriter(sw);
                JObject objChild = new JObject();
                JObject objParent = new JObject();

                foreach (var item in EmployeeList)
                {

                    DataView dtView = dTable.DefaultView;
                    dtView.RowFilter = "EmployeeName='" + item.ToString() + "'";
                    DataTable dtNew = dtView.ToTable();
                    int Count = 0;

                    foreach (DataRow row in dtNew.Rows)
                    {
                        objChild = new JObject(
                                        new JProperty(row["Year"].ToString(),
                                            new JObject(
                                                new JProperty("StartRange", Convert.ToInt32(row["StartRange"].ToString())), new JProperty("EndRange", Convert.ToInt32(row["EndRange"])))));
                        if (Count == 0 )
                            {                               
                               objParent.Merge(new JObject(new JProperty(item.ToString(), objChild)));                                 
                            }
                            else
                            {
                               objParent.Merge(objChild);                                
                            }                       
                        Count++;
                    }                   
                }
                sw.Write(objParent);
                sw.Close();
            }
        }

but the reusult JSON is like below with issues.

{
  "Employee1": {
    "Year1": {
      "StartRange": 11,
      "EndRange": 22
    }
  },
  "Year2": {
    "StartRange": 22,
    "EndRange": 45
  },
  "Employee2": {
    "Year1": {
      "StartRange": 11,
      "EndRange": 33
    }
  },
  "Year2": {
    "StartRange": 11,
    "EndRange": 35
  }
}

The DataTable will have the follwing table data

EmployeeName    Years   StartRange  EndRange
Employee2       Year1   22          35
Employee2       Year2   35          48
Employee1       Year1   12          22
Employee1       Year2   22          32

What is the maistake I have done?. Please help me to sort out this issue.

Prevoiusly I was using DataTable and now I am Using List for keeping data from Database. here is the code and I am getting the JSON file with repeated values.

  public class ConfigInfo

{
    public string ParentGroup;
    public string Label;
    public int ID;
    public int StartRange;
    public int EndRange;

}

and creating List

List<ConfigInfo> configInfoList = new List<ConfigInfo>();
    ConfigInfo configInfo = new ConfigInfo();

                    configInfo.ParentGroup = "Employee1";
                    configInfo.StartRange = 11;
                    configInfo.EndRange = 22;
                    configInfo.Label = "YYY";

                    configInfoList.Add(configInfo);
                    configInfo = new ConfigInfo();

                    configInfo.ParentGroup = "Employee2";
                    configInfo.StartRange = 24;
                    configInfo.EndRange = 56;
                    configInfo.Label = "XXX";

                    configInfoList.Add(configInfo);



if (!File.Exists(fileName))
            {
                FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write);
                StreamWriter sw = new StreamWriter(fs);

                JsonTextWriter writer = new JsonTextWriter(sw);

                Dictionary<string, Dictionary<string, LabelData>> data = GetData(configInfoList); // Here you do the reading
                string json = JsonConvert.SerializeObject(data,Formatting.Indented);
                sw.Write(json);
                sw.Close();
            }

and now GetData() is called

public Dictionary<string, Dictionary<string, LabelData>> GetData(List<ConfigInfo> configList)
        {
            var labelData = new Dictionary<string, Dictionary<string, LabelData>>();

            foreach (var listItem in configList)
            {
                labelData[listItem.ParentGroup] = configList.Distinct().ToDictionary(x => x.Label.ToString(), row => new LabelData()
                {
                    StartRange = Convert.ToInt32(listItem.StartRange.ToString()),
                    EndRange = Convert.ToInt32(listItem.EndRange.ToString())
                });
            }

            return labelData;
        }

and the resultant JSON as follows

{
  "Employee1": {
    "YYY": {
      "StartRange": 11,
      "EndRange": 22
    },
    "XXX": {
      "StartRange": 11,
      "EndRange": 22
    }
  },
  "Employee2": {
    "YYY": {
      "StartRange": 24,
      "EndRange": 56
    },
    "XXX": {
      "StartRange": 24,
      "EndRange": 56
    }
  }
}
5
  • What issues! The output JSON looks fine to me, Commented May 12, 2016 at 7:03
  • 1
    Your mistake is to not clearly putting up your question Commented May 12, 2016 at 7:06
  • the arrangement of curly braces are not well in the output Commented May 12, 2016 at 7:12
  • Dai, please check the curly braces Commented May 12, 2016 at 7:13
  • Employee is the parent object ,year is child object of Employee and startRange and EndRange are child objects of year. The problem with the merging of child object with respective parent object. Commented May 12, 2016 at 7:17

1 Answer 1

3

your mistake is that you are overdoing this. I will let aside the code that reads the data, because it is utterly confusing.

The thing you must do is strongly define your output structure:

public class YearData
{
    public int StartRange { get; set; }
    public int EndRange { get; set; }
}

Your desired output is a Dictionary<string, Dictionary<string, YearData>>. That is, a dictionary having employees as keys, and dictionary of year/yearData pairs as values.

When you have it, the serialization is simple:

Dictionary<string, Dictionary<string, YearData>> data = GetEmployeeData(); // Here you do the reading
string json = JsonConvert.SerializeObject(data);

And the serialization is done. So, now the real problem is to manipulate your data to populate this structure. But I think you can manage to do it by yourself.

Edit: about the reading part. You probably could do it like this (untested, I don't know even if compiles, but should give you a quick start):

var employeeData = new Dictionary<string, Dictionary<string, YearData>>();
foreach(var employeeName in EmployeeList)
{
  DataView dtView = dTable.DefaultView;
  dtView.RowFilter = "EmployeeName='" + employeeName.ToString() + "'";
  DataTable dtNew = dtView.ToTable();

  employeeData[employeeName] = dtNew.Rows.ToDictionary(row => row["Year"].ToString(), row => new YearData()
    {
      StartRange = Convert.ToInt32(row["StartRange"].ToString())),
      EndRange = Convert.ToInt32(row["EndRange"].ToString()))
    });
}

And then serialize like above.

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

7 Comments

Thanks for your reply. But I couldn't understand your code and how to implement the method definition for GetEmployeeData().
And your code has some syntax errors. cound not compile.
Error 1 'System.Data.DataRowCollection' does not contain a definition for 'ToDictionary' and no extension method 'ToDictionary' accepting a first argument of type 'System.Data.DataRowCollection' could be found (are you missing a using directive or an assembly reference?) for the code dtNew.Rows.ToDictionary(row => row["Year"].ToString(), row => new YearData()
It' Linq. Do you know what Linq is? You need a using System.Linq statement.
|

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.