首页 > 解决方案 > 该值不断被循环替换

问题描述

我面临的问题是,json[]将不断被新价值取代。
我想要实现的是存储所有值。
我已经尝试过json[index][xxx],但它仍然无法正常工作。

var json = new JObject();
for(int index = 0; index < employeeCareerProgression.Count; index++)
{
    json["Desc"] = employeeCareerProgression[index].Description;
    json["Date"] = employeeCareerProgression[index].ProgressionStartDate;
}

标签: c#json

解决方案


您必须向您的 JObject 添加一个新的 JProperty - 您正在为每个循环的相同属性设置一个新值。

试试这个,它可能对你有用。不过我还没有测试过。

var json = new JObject();
for(var index = 0; index < employeeCareerProgression.Count; index++)
{
  json.Add(new JProperty(index, // You could change this index to a more descriptive field on your employeeCareerProgression object (maybe the primary key, or employee name?)
    new JObject
    {
      new JProperty("Desc", employeeCareerProgression[index].Description),
      new JProperty("Date", employeeCareerProgression[index].ProgressionStartDate),
    }
  );
}

您最终应该得到这样的 JSON:

{[
  '0': {
     'Desc': 'DESCRIPTION',
     'Date': '2020-12-14T00:00:00Z'
  }, 
  '1': {
     ...
  }
]}

推荐阅读