C#对象的JSON字符串



我想创建一个具有以下格式的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:UsersDocumentsJSONJsonConfig" + 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();
            }
        }

但是result 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

我干了什么?。请帮我解决这个问题。

以前我使用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
    }
  }
}

您的错误是做得太过火了。我将把读取数据的代码放在一边,因为它完全令人困惑。

你必须做的是严格定义你的输出结构:

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

您想要的输出是Dictionary<string, Dictionary<string, YearData>>。也就是说,一个以employees为键、以dictionary of year/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()))
    });
}

然后像上面那样序列化。

相关内容

  • 没有找到相关文章

最新更新