来自C#对象的JSON字符串

时间:2016-05-12 07:01:21

标签: c# json json.net

我想创建一个具有以下格式的JSON文件。

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

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

这是我的C#代码获取JSON格式

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();
            }
        }

但是reusult JSON就像下面的问题一样。

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

DataTable将具有以下表格数据

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

我做过的是什么?请帮我解决这个问题。

Prevoiusly我正在使用DataTable,现在我使用List来保存数据库中的数据。这是代码,我得到重复值的JSON文件。

  public class ConfigInfo

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

}

并创建列表

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();
            }

现在调用GetData()

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;
        }

和结果JSON如下

{
  "Employee1": {
    "YYY": {
      "StartRange": 11,
      "EndRange": 22
    },
    "XXX": {
      "StartRange": 11,
      "EndRange": 22
    }
  },
  "Employee2": {
    "YYY": {
      "StartRange": 24,
      "EndRange": 56
    },
    "XXX": {
      "StartRange": 24,
      "EndRange": 56
    }
  }
}

1 个答案:

答案 0 :(得分:3)

你的错误就是你过度了。 我会放弃读取数据的代码,因为它完全令人困惑。

你必须做的是强烈定义你的输出结构:

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

您想要的输出是Dictionary<string, Dictionary<string, YearData>>。 也就是说,以雇员作为键的字典,以及年/年数据字典对作为值。

当你拥有它时,序列化很简单:

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

序列化完成。 所以,现在真正的问题是操纵你的数据来填充这个结构。但我认为你可以自己做到这一点。

编辑:关于阅读部分。 你可能会这样做(未经测试,我不知道即使编译,但应该给你一个快速的开始):

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()))
    });
}

然后像上面那样序列化。